package com.restmatic.restautomation.vc.sc;


import com.acme.model.domain.sc.entity.Section;
import com.acme.model.domain.sc.entity.Table;
import com.acme.model.domain.sc.sessionbean.SCManager;
import com.acme.structure.BaseEntity;
import com.acme.structure.BaseEntityListener;
import com.acme.structure.GridData;
import com.acme.structure.ServerResponse;
import com.acme.structure.ServiceLocator;
import com.acme.structure.component.BaseRow;
import com.acme.structure.util.ConversionUtil;
import com.acme.structure.util.ObjectUtil;
import com.acme.structure.util.datalist.ListManager;
import com.acme.util.ui.UIHelper;
import com.acme.util.ui.WindowManager;
import com.acme.util.ui.bean.ToolbarMBean;
import com.acme.util.utilities.ADFUtils;
import com.acme.util.utilities.JSFUtils;
import com.acme.vcutil.supplier.BranchSupplier;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Vector;

import javax.ejb.EJB;

import javax.faces.event.ActionEvent;

import javax.naming.NamingException;

import oracle.adf.view.rich.component.rich.data.RichTable;
import oracle.adf.view.rich.component.rich.layout.RichShowDetailItem;

import org.apache.myfaces.trinidad.model.RowKeySet;
import org.apache.myfaces.trinidad.model.RowKeySetImpl;


public class SectionMBean extends ToolbarMBean
{
    private GridData data = new GridData();
    @EJB
    SCManager managerBean;
    private Vector baseRowCollection = new Vector();
    private static String ENTITYTABLECOMPONENTID = "entityT";
    private static String TABLETABLECOMPONENTID = "tableT";
    private static String MAINPANELTABBEDCOMPONENTID = "pt_main";
    private BranchSupplier branchSupplier;

    private RowKeySet entityTableRowKeySet = null;
    private RowKeySet tableTableRowKeySet = null;

    public SectionMBean()
    {
        try
        {
            managerBean = (SCManager)ServiceLocator.getInstance().getResource("ejb/SCManager/remote", SCManager.class);
        }
        catch (NamingException e)
        {
            e.printStackTrace();
        }
    }

    public void init()
    {
        try
        {
            if (ObjectUtil.isNull(branchSupplier = (BranchSupplier)ListManager.getInstance().getSupplier("branchs")))
                branchSupplier = new BranchSupplier();

            if (managerBean != null)
            {
                Collection<BaseEntity> collection = managerBean.findSections();
                Collections.sort((List<BaseEntity>)collection);
                data.initializeGridData(collection);
                baseRowCollection.clear();
                baseRowCollection.addAll(ConversionUtil.getTransformedBaseRowCollection(data.getDataCollection()));
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    public void saveButtonPressed(ActionEvent actionEvent)
    {
        try
        {
            ServerResponse responseData = managerBean.synchronizeSections(data);
            Collection exceptionList = responseData.getExceptionList();
            if (exceptionList.isEmpty())
            {
                Collection collection = responseData.getReturnData();
                data.updateDataCollectionWithSynch(collection);
                Collections.sort((List)data.getDataCollection());
                baseRowCollection.clear();
                baseRowCollection.addAll(ConversionUtil.getTransformedBaseRowCollection(data.getDataCollection()));
                UIHelper.showInformationMessage(WindowManager.getInstance().getStatusUtil().incomingSuccessMsg());
            } else
                UIHelper.showInformationMessages(WindowManager.getInstance().getHandler().handleExceptions(exceptionList));
        }
        catch (Exception exc)
        {
            UIHelper.showInformationMessages(WindowManager.getInstance().getHandler().handleException(exc));
        }
    }

    private BaseRow createBaseRow()
    {
        BaseRow row = new BaseRow(new Section());
        return row;
    }

    public void addButtonPressed(ActionEvent actionEvent)
    {
        int entityStatus;
        BaseRow baseRow = null;
        RichShowDetailItem activePanelTab = (RichShowDetailItem)JSFUtils.findActiveTabInPanelTabbed(MAINPANELTABBEDCOMPONENTID);
        if ("sdi_section".equals(activePanelTab.getId()))
        {
            entityStatus = BaseEntityListener.ENTITY_STATUS_PERSISTED;
            baseRow = createBaseRow();
        } else
        {
            entityStatus = BaseEntityListener.ENTITY_STATUS_UPDATED;
            baseRow = getSelectedMainBaseRow();
            ((Section)baseRow.getBaseEntity()).getTables().add(new Table());
        }

        updateDataCollection(baseRow, entityStatus);
    }

    public void removeButtonPressed(ActionEvent event)
    {
        int entityStatus;
        BaseRow baseRow = null;
        RichShowDetailItem activePanelTab = (RichShowDetailItem)JSFUtils.findActiveTabInPanelTabbed(MAINPANELTABBEDCOMPONENTID);
        if ("sdi_section".equals(activePanelTab.getId()))
        {
            entityStatus = BaseEntityListener.ENTITY_STATUS_REMOVED;
            baseRow = getSelectedMainBaseRow();
        } else
        {
            entityStatus = BaseEntityListener.ENTITY_STATUS_UPDATED;
            baseRow = getSelectedMainBaseRow();
            ((Section)baseRow.getBaseEntity()).getTables().remove(getSelectedRoleGroupTableRowObject());
        }

        updateDataCollection(baseRow, entityStatus);
    }

    private void updateDataCollection(BaseRow baseRow, int entityStatus)
    {
        switch (entityStatus)
        {
        case BaseEntityListener.ENTITY_STATUS_PERSISTED:
            {
                baseRowCollection.add(0, baseRow);
                data.getDataCollection().add(0, baseRow.getBaseEntity());
                data.getNewBuffer().add(baseRow.getBaseEntity());
                break;
            }
        case BaseEntityListener.ENTITY_STATUS_UPDATED:
            {
                if (!data.getNewBuffer().contains(baseRow.getBaseEntity()) && !data.getUpdatedBuffer().contains(baseRow.getBaseEntity()))
                    data.getUpdatedBuffer().add(baseRow.getBaseEntity());
                break;
            }
        case BaseEntityListener.ENTITY_STATUS_REMOVED:
            {
                if (data.getNewBuffer().contains(baseRow.getBaseEntity()))
                {
                    data.getNewBuffer().remove(baseRow.getBaseEntity());
                    data.getDataCollection().remove(baseRow.getBaseEntity());
                    baseRowCollection.remove(baseRow);
                } else
                {
                    data.getGarbageData().add(baseRow.getBaseEntity());
                    data.getDataCollection().remove(baseRow.getBaseEntity());
                    baseRowCollection.remove(baseRow);
                }
            }
        default:
            break;
        }
    }

    public void rollbackButtonPressed(ActionEvent actionEvent)
    {
        data.getDataCollection().clear();
        data.getGarbageData().clear();
        data.getNewBuffer().clear();
        data.getUpdatedBuffer().clear();
        data.getDataCollection().addAll(data.getSynchBuffer());
        baseRowCollection.clear();
        baseRowCollection.addAll(ConversionUtil.getTransformedBaseRowCollection(data.getDataCollection()));
    }

    public void update(ActionEvent actionEvent)
    {
        RichTable entityT = (RichTable)JSFUtils.findComponentInRoot(ENTITYTABLECOMPONENTID);
        BaseRow baseRow = (BaseRow)entityT.getSelectedRowData();
        baseRow.getRowProperties().setUpdateable(true);
        if (!data.getUpdatedBuffer().contains(baseRow.getBaseEntity()))
        {
            data.getUpdatedBuffer().add(baseRow.getBaseEntity());
        }
    }

    public Section getSelectedMainEntity()
    {
        return (Section)getSelectedMainBaseRow().getBaseEntity();
    }

    public BaseRow getSelectedMainBaseRow()
    {
        if (getSelectedEntityTableRowObject() != null)
            return (BaseRow)getSelectedEntityTableRowObject();
        else if (!baseRowCollection.isEmpty())
            return (BaseRow)baseRowCollection.get(0);
        else
            return new BaseRow();
    }

    private Object getSelectedRoleGroupTableRowObject()
    {
        return ADFUtils.getSelectedTableRowObject(TABLETABLECOMPONENTID);
    }

    private Object getSelectedEntityTableRowObject()
    {
        return ADFUtils.getSelectedTableRowObject(ENTITYTABLECOMPONENTID);
    }

    public void setBaseRowCollection(Vector baseRowCollection)
    {
        this.baseRowCollection = baseRowCollection;
    }

    public Vector getBaseRowCollection()
    {
        return baseRowCollection;
    }

    public void setGridData(GridData data)
    {
        this.data = data;
    }

    public GridData getGridData()
    {
        return data;
    }

    public BranchSupplier getBranchSupplier()
    {
        return branchSupplier;
    }

    public void setManagerBean(SCManager managerBean)
    {
        this.managerBean = managerBean;
    }

    public SCManager getManagerBean()
    {
        return managerBean;
    }

    public void setEntityTableRowKeySet(RowKeySet entityTableRowKeySet)
    {
        this.entityTableRowKeySet = entityTableRowKeySet;
    }

    public RowKeySet getEntityTableRowKeySet()
    {
        if (entityTableRowKeySet == null)
        {
            RowKeySet selectedRowKeySet = new RowKeySetImpl();
            selectedRowKeySet.add(0);
            entityTableRowKeySet = selectedRowKeySet;
        }
        return entityTableRowKeySet;
    }

    public void setTableTableRowKeySet(RowKeySet tableTableRowKeySet)
    {
        this.tableTableRowKeySet = tableTableRowKeySet;
    }

    public RowKeySet getTableTableRowKeySet()
    {
        if (entityTableRowKeySet == null)
        {
            RowKeySet selectedRowKeySet = new RowKeySetImpl();
            selectedRowKeySet.add(0);
            entityTableRowKeySet = selectedRowKeySet;
        }
        return entityTableRowKeySet;
    }
}
