package com.restmatic.restautomation.vc.sc;


import com.acme.model.domain.ad.entity.Currency;
import com.acme.model.domain.sc.entity.Service;
import com.acme.model.domain.sc.entity.ServiceContent;
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.ContentTypeSupplier;
import com.acme.vcutil.supplier.CurrencySupplier;
import com.acme.vcutil.supplier.SellingStatusSupplier;
import com.acme.vcutil.supplier.ServiceGroupSupplier;
import com.acme.vcutil.supplier.UnitGroupSupplier;

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 ServiceMBean extends ToolbarMBean
{
    private GridData data = new GridData();
    @EJB
    SCManager managerBean;
    private Vector baseRowCollection = new Vector();
    private static String MAINPANELTABBEDCOMPONENTID = "pt_main";
    private static String ENTITYTABLECOMPONENTID = "entityT";
    private static String CONTENTTABLECOMPONENTID = "contentT";

    private RowKeySet entityTableRowKeySet = null;
    private RowKeySet contentTableRowKeySet = null;

    private UnitGroupSupplier unitGroupSupplier;
    private ServiceGroupSupplier serviceGroupSupplier;
    private CurrencySupplier currencySupplier;
    private SellingStatusSupplier sellingStatusSupplier;
    private ContentTypeSupplier contentTypeSupplier;

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

    public void init()
    {
        try
        {
            if (ObjectUtil.isNull(unitGroupSupplier = (UnitGroupSupplier)ListManager.getInstance().getSupplier("unitgroups")))
                unitGroupSupplier = new UnitGroupSupplier();
            if (ObjectUtil.isNull(serviceGroupSupplier = (ServiceGroupSupplier)ListManager.getInstance().getSupplier("servicegroups")))
                serviceGroupSupplier = new ServiceGroupSupplier();
            if (ObjectUtil.isNull(currencySupplier = (CurrencySupplier)ListManager.getInstance().getSupplier("currencies")))
                currencySupplier = new CurrencySupplier();
            if (ObjectUtil.isNull(sellingStatusSupplier = (SellingStatusSupplier)ListManager.getInstance().getSupplier("sellingstatuses")))
                sellingStatusSupplier = new SellingStatusSupplier(false);
            if (ObjectUtil.isNull(contentTypeSupplier = (ContentTypeSupplier)ListManager.getInstance().getSupplier("contenttypes")))
                contentTypeSupplier = new ContentTypeSupplier();

            if (managerBean != null)
            {
                Collection<BaseEntity> collection = managerBean.findServices();
                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.synchronizeServices(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()
    {
        Service entity=new Service();
        setDefaultValues(entity);
        BaseRow row = new BaseRow(entity);
        return row;
    }

    private void setDefaultValues(Service entity)
    {
        entity.setCurrency((Currency)currencySupplier.getDefaultValue());
    }

    public void addButtonPressed(ActionEvent actionEvent)
    {
        int entityStatus;
        BaseRow baseRow = null;
        RichShowDetailItem activePanelTab = (RichShowDetailItem)JSFUtils.findActiveTabInPanelTabbed(MAINPANELTABBEDCOMPONENTID);
        if ("sdi_service".equals(activePanelTab.getId()))
        {
            entityStatus = BaseEntityListener.ENTITY_STATUS_PERSISTED;
            baseRow = createBaseRow();
        } else if (getSelectedMainBaseRow().getBaseEntity() == null || !getSelectedMainBaseRow().getRowProperties().isUpdateable())
            return;
        else if ("sdi_content".equals(activePanelTab.getId()))
        {
            entityStatus = BaseEntityListener.ENTITY_STATUS_UPDATED;
            baseRow = getSelectedMainBaseRow();
            ((Service)baseRow.getBaseEntity()).getContents().add(new ServiceContent());
        } else
            return;

        updateDataCollection(baseRow, entityStatus);
    }

    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 void removeButtonPressed(ActionEvent event)
    {
        int entityStatus;
        BaseRow baseRow = null;
        RichShowDetailItem activePanelTab = (RichShowDetailItem)JSFUtils.findActiveTabInPanelTabbed(MAINPANELTABBEDCOMPONENTID);

        if ("sdi_service".equals(activePanelTab.getId()))
        {
            entityStatus = BaseEntityListener.ENTITY_STATUS_REMOVED;
            baseRow = getSelectedMainBaseRow();
        } else if ("sdi_content".equals(activePanelTab.getId()))
        {
            entityStatus = BaseEntityListener.ENTITY_STATUS_UPDATED;
            baseRow = getSelectedMainBaseRow();
            ((Service)baseRow.getBaseEntity()).getContents().remove(getSelectedServiceContent());
        } else
            return;

        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 rollback(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 ServiceContent getSelectedServiceContent()
    {
        return (ServiceContent)ADFUtils.getSelectedTableRowObject(CONTENTTABLECOMPONENTID);
    }

    public Service getSelectedMainEntity()
    {
        return (Service)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 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 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 setContentTableRowKeySet(RowKeySet unitTableRowKeySet)
    {
        this.contentTableRowKeySet = unitTableRowKeySet;
    }

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

    public UnitGroupSupplier getUnitGroupSupplier()
    {
        return unitGroupSupplier;
    }

    public ServiceGroupSupplier getServiceGroupSupplier()
    {
        return serviceGroupSupplier;
    }

    public CurrencySupplier getCurrencySupplier()
    {
        return currencySupplier;
    }

    public SellingStatusSupplier getSellingStatusSupplier()
    {
        return sellingStatusSupplier;
    }

    public ContentTypeSupplier getContentTypeSupplier()
    {
        return contentTypeSupplier;
    }
}
