package page.tools.entity;

import org.wikiwebserver.core.Privilege;
import org.wikiwebserver.handler.http.HTTPHandler;

/**
 * A Payment object stores the information about a payment
 * 
 * @author Michael Gardiner
 *
 */
public class Comment extends ProtectedStorable {
    
    public String getType() {
        return "Comment";
    } 
    
    public Comment(String text, HTTPHandler conn) {
        super();
        User author = User.getUser(conn.getRequest());        
        if (canModify(conn)) {  
            put("created", new Long(System.currentTimeMillis()));
            put("authorUserID", author.getId());        
            put("text", text);
        }
        else throw new SecurityException(author.getPrivilege() + 
                       " users can not create comments");
    }
    
    private Comment(String id) {
        super(id);
    }        
    
    public String getText() {
        return (String) get("text");
    }     
    
    public void setText(String text, HTTPHandler conn) {
        if (canModify(conn)) {
            put("text", text);
        }
        else throw new SecurityException("Permission denied");
    }
    
    public boolean canModify(HTTPHandler conn) {
        User operator = User.getUser(conn.getRequest());
        if (operator == null) return false;
        
        return (operator.getPrivilege().isAbove(Privilege.PREMIUM_USER)) ||
               ((getAuthor() == null || operator.equals(getAuthor())) &&
                operator.getPrivilege().isAbove(Privilege.GUEST));
    }
  
    public User getAuthor() {
        String authorUserID = (String) get("authorUserID");
        if (authorUserID == null) return null;
        return User.getUserById(authorUserID);
    }    
    
    public static Comment getCommentById(String id) {
        Comment c = new Comment(id);
        if (c.isValid()) return c;
        // Not created
        return null;
    }      
    
    public void clear(HTTPHandler conn) {
        if (canModify(conn)) {
            super.clear();
        }
    }
    
    protected void checkCanClear() {
        // Comments can be deleted
    }    
}

