package jp.sf.pal.todolist.bean;

import java.util.ArrayList;
import java.util.Map;

import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.model.DataModel;

import jp.sf.pal.todolist.TodoListConstants;
import jp.sf.pal.todolist.model.Todo;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.seasar.portlet.util.PortletResourceBundleUtil;

import com.marevol.utils.faces.application.FacesMessageUtil;
import com.marevol.utils.faces.model.S2HibernateDataModel;
import com.marevol.utils.faces.util.LocaleUtil;

public class TodoListViewPageBean
{
    /**
     * Logger for this class
     */
    private static final Log log = LogFactory
            .getLog(TodoListViewPageBean.class);

    private TodoListViewSessionBean todoListViewSession;

    private Boolean validUser;

    public String detail()
    {
        ExternalContext exContext = FacesContext.getCurrentInstance()
                .getExternalContext();
        Map map = exContext.getRequestMap();
        Map blogMap = (Map) map.get("todo");
        Todo todo = (Todo) blogMap.get("0");
        if (todo != null)
        {
            getTodoListViewSession().setTodo(todo);
            return TodoListConstants.TODOLISTEDIT_VIEW_ID;
        }
        else
        {
            // i18n
            FacesMessageUtil.addWarnMessage(PortletResourceBundleUtil
                    .getString(LocaleUtil.getLocale(),
                            "todolistviewpagebean.TheSelectedItemIsNull"));
            log.error("The selected Item is null.");
        }
        return null;
    }

    public String displayAll()
    {
        getTodoListViewSession().setAll(Boolean.TRUE);
        return null;
    }

    public String displayOpen()
    {
        getTodoListViewSession().setAll(Boolean.FALSE);
        return null;
    }

    public String toAddPage()
    {
        return TodoListConstants.TODOLISTADD_VIEW_ID;
    }

    // Setter and Getter

    /**
     * @return Returns the todo items.
     */
    public DataModel getTodos()
    {
        StringBuffer query = new StringBuffer("select todo from Todo todo ");
        String param = "where ";
        ArrayList paramList = new ArrayList();

        if (getTodoListViewSession().getOwner().equals(""))
        {
            if (FacesContext.getCurrentInstance().getExternalContext()
                    .getRemoteUser() == null)
            {
                query.append(param);
                query.append("todo.viewmode = ? ");
                param = "and ";
                paramList.add(TodoListConstants.PUBLIC_VIEW_MODE);
            }
        }
        else
        {

            if (getTodoListViewSession().getOwner().equals(
                    FacesContext.getCurrentInstance().getExternalContext()
                            .getRemoteUser()))
            {
                query.append(param);
                query.append("todo.owner = ? ");
                param = "and ";
                paramList.add(getTodoListViewSession().getOwner());
            }
            else
            {
                query.append(param);
                query.append("todo.owner = ? ");
                param = "and ";
                paramList.add(getTodoListViewSession().getOwner());

                query.append(param);
                query.append("todo.viewmode = ? ");
                param = "and ";
                paramList.add(TodoListConstants.PUBLIC_VIEW_MODE);
            }
        }

        // if displaying all items
        if (!getTodoListViewSession().getAll().booleanValue())
        {
            query.append(param);
            query.append("todo.status != ? ");
            param = "and ";
            paramList.add(TodoListConstants.STATUS_100);
        }

        query.append("order by todo.duedate");

        if (log.isDebugEnabled())
        {
            log.debug("getTodoItems() -  : query=" + query.toString());
        }

        Object[] params = new Object[paramList.size()];
        for (int i = 0; i < paramList.size(); i++)
        {
            params[i] = paramList.get(i);
        }

        return new S2HibernateDataModel(query.toString(), params);
    }

    /**
     * @return Returns the todoListViewSession.
     */
    public TodoListViewSessionBean getTodoListViewSession()
    {
        return todoListViewSession;
    }

    /**
     * @param todoListViewSession The todoListViewSession to set.
     */
    public void setTodoListViewSession(TodoListViewSessionBean todoListSession)
    {
        this.todoListViewSession = todoListSession;
    }

    public Boolean getValidUser()
    {
        if (validUser == null)
        {
            String username = FacesContext.getCurrentInstance()
                    .getExternalContext().getRemoteUser();
            if (username != null)
            {
                validUser = Boolean.TRUE;
            }
            else
            {
                validUser = Boolean.FALSE;
            }
        }
        return validUser;
    }

}
