/*
 * Copyright 2006-2007 Queplix Corp.
 *
 * Licensed under the Queplix Public License, Version 1.1.1 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.queplix.com/solutions/commercial-open-source/queplix-public-license/
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 *
 */

package com.queplix.qwoss.client.frames.mainframe;

import com.queplix.core.client.app.vo.EntityData;
import com.queplix.core.client.app.vo.FamgMeta;
import com.queplix.core.client.app.vo.FieldData;
import com.queplix.core.client.app.vo.ListboxFieldData;
import com.queplix.core.client.app.vo.SubsetData;
import com.queplix.core.client.app.vo.TextboxFieldData;
import com.queplix.core.client.common.ui.DialogHelper;
import com.queplix.core.client.controls.datefield.DateHelper;
import com.queplix.core.client.frames.mainframe.FormOperations;
import com.queplix.core.client.frames.mainframe.FormState;
import java.util.Collection;
import java.util.Date;

/**
 * Description:
 *
 * @author rustem.nizamiev, sergei.savchuk
 * @since 15 ßíâàðü 2007 ã., 20:35
 */
public class InteractionHandler extends OSSOperationStrategy {

    private static final String FORM_CREATE_TICKET_BUTTON
            = "FORM_CREATE_TICKET_BUTTON";
    private static final String FORM_HANGUP_BUTTON = "FORM_HANGUP_BUTTON";
    private static final String INTERACTION_ID_FIELD = "qw_interactionid";
    private static final String INTERACTION_SOURCE_FIELD = "qw_source";
    private static final String INTERACTION_AGENT_ID_FIELD = "qw_agentid";
    private static final String INTERACTION_CUSTOMER_ID_FIELD = "qw_customerid";
    private static final String INTERACTION_EMPLOYEE_ID_FIELD = "qw_employeeid";
    private static final String INTERACTION_SUBJECT_FIELD = "qw_problem";
    private static final String INTERACTION_DESCRIPTION_FIELD = "qw_description";
    private static final String INTERACTION_PHONETIME_FIELD = "qw_phonetime";
    private static final String INTERACTION_LINKTICKET_FIELD = "linked_tickets";

    private static final String CUR_INTERACTION_ID_FIELD = "qw_cur_interaction";
    private static final String TICKET_SOURCE_FIELD = "qw_source";
    private static final String TICKET_AGENT_ID_FIELD = "qw_agentid";
    private static final String TICKET_CUSTOMER_ID_FIELD = "qw_customerid";
    private static final String TICKET_EMPLOYEE_ID_FIELD = "qw_employeeid";
    private static final String TICKET_SUBJECT_FIELD = "qw_problem";
    private static final String TICKET_DESCRIPTION_FIELD = "qw_description";

    private static final String INTER_TICKET_ENTITY = "inter_ticket.linkset";
    private static final String INTER_TICKET_FILTER_FIELD = "qw_interactionid";

    private Date newPressDate;

    /*
     * Ticket form id
     * It should initialized in HandlerFactory or it's siblings
     */
    private String ticketFormId;

    // Ties with other handlers
    private TicketHandler ticketHandler;

    public void createRecordProtorype(
            Collection data) {
        super.createRecordProtorype(data);
        newPressDate = DateHelper.getUserDate();
    }

    protected void createRecordProtorypeResponse(boolean success,
                                                 FieldData[] fields,
                                                 Long rowId) {
        super.createRecordProtorypeResponse(success, fields, rowId);

        if(success) {
            getOperationContext().getFormOperations().clearFormField(
                    getFormIndex(), INTERACTION_LINKTICKET_FIELD);
        }
    }

    protected boolean processFilteredLink(String linkedForm, 
            FormOperations formContext, FamgMeta.Index formIndex){
        if(linkedForm.equalsIgnoreCase( ticketFormId)) { // the link for ticket form is pressed
            EntityData linkFilter =  new EntityData(INTER_TICKET_ENTITY, new Long(-1),
                    new FieldData[]{ new TextboxFieldData(INTER_TICKET_FILTER_FIELD,
                         formContext.getSelectedRecordId(formIndex).toString()) });
            ticketHandler.addExternalFilter(linkFilter);
            return CONTINUE;
        }
        return BREAK;
    }

    public void handleCustomButtonEvent(String buttonId) {
        FamgMeta.Index formIndex = getFormIndex();
        FormOperations context = getOperationContext().getFormOperations();
        int state = context.getFormState(formIndex);
        if(buttonId.equalsIgnoreCase(FORM_CREATE_TICKET_BUTTON)) {
            switch(state) {
                case FormState.SELECTED_STATE:
                case FormState.EDIT_STATE:
                case FormState.NEW_STATE:
                    createTicketFromNewState(formIndex);
                    break;
                default:
                    DialogHelper.showModalMessageDialog(
                            "This button is available only in NEW, EDIT or SELECTED state.");
            }
        } else if(buttonId.equalsIgnoreCase(FORM_HANGUP_BUTTON)) {
            switch(state) {
                case FormState.NEW_STATE:
                    fillPhoneTime(formIndex);
                    break;
                default:
                    DialogHelper.showModalMessageDialog(
                            "This button is available only in NEW state.");
            }
        }
    }

    private void fillPhoneTime(FamgMeta.Index interationFormIndex) {
        String warnMsg
                = "This button is available only if communication type is kind of call.";
        FormOperations formContext = getOperationContext().getFormOperations();
        FieldData interSource = formContext.getFieldData(interationFormIndex,
                INTERACTION_SOURCE_FIELD);
        if(interSource.isEmpty()) {
            DialogHelper.showModalMessageDialog(warnMsg);
            return;
        }
        long selId = ((ListboxFieldData) interSource).getItemsSelected()
                .getSelectedIDs()[0];
        switch((int) selId) {
            case InteractionHelper.INC_CALL_SRC:
            case InteractionHelper.OUT_CALL_SRC:
                //Date newPressDate = ((DateFieldData)interactionModel.getElementData(INTERACTION_RECEIVED_FIELD)).getStartDate();
                Date curDate = DateHelper.getUserDate();
                String diffTime = "";
                if(curDate != null && newPressDate != null) {
                    long diffSec = (curDate.getTime() - newPressDate.getTime())
                            / 1000;
                    diffTime = OperationsHelper.formatToTime(diffSec);
                }
                formContext.setFieldData(interationFormIndex,
                        new TextboxFieldData(INTERACTION_PHONETIME_FIELD,
                                diffTime));
                break;
            default:
                DialogHelper.showModalMessageDialog(warnMsg);
        }
    }

    protected FieldData[] createInitData(FormOperations context, FamgMeta.Index formIndex){
        FieldData interId = context.getFieldData(formIndex,
                INTERACTION_ID_FIELD);
        FieldData interSource = context.getFieldData(formIndex,
                INTERACTION_SOURCE_FIELD);
        FieldData interCustomer = context.getFieldData(formIndex,
                INTERACTION_CUSTOMER_ID_FIELD);
        FieldData interEmployee = context.getFieldData(formIndex,
                INTERACTION_EMPLOYEE_ID_FIELD);
        FieldData interAgent = context.getFieldData(formIndex,
                INTERACTION_AGENT_ID_FIELD);
        FieldData interSubject = context.getFieldData(formIndex,
                INTERACTION_SUBJECT_FIELD);
        FieldData interDescription = context.getFieldData(formIndex,
                INTERACTION_DESCRIPTION_FIELD);

        FieldData clonedInterId = interId.cloneData();
        clonedInterId.setFieldID(CUR_INTERACTION_ID_FIELD);
        FieldData clonedInitiator = null;
        FieldData clonedSource = null;
        FieldData clonedAgent = null;
        FieldData clonedSubject = null;
        FieldData clonedDescription = null;

        if(!interCustomer.isEmpty() && !interEmployee.isEmpty()) {
            if(DialogHelper.showModalQuestionDialog(
                    "You have to transfer to Ticket form either Customer or Employee.\n"
                            +
                            "Press OK to proceed with Customer or CANCEL to break process.")
                    != 1) {
                return null;
            }
            clonedInitiator = interCustomer.cloneData();
            clonedInitiator.setFieldID(TICKET_CUSTOMER_ID_FIELD);
        } else {
            if(!interCustomer.isEmpty()) {
                clonedInitiator = interCustomer.cloneData();
                clonedInitiator.setFieldID(TICKET_CUSTOMER_ID_FIELD);
            } else if(!interEmployee.isEmpty()) {
                clonedInitiator = interEmployee.cloneData();
                clonedInitiator.setFieldID(TICKET_EMPLOYEE_ID_FIELD);
            }
        }
        if(!interSource.isEmpty()) {
            long selId = ((ListboxFieldData) interSource).getItemsSelected()
                    .getSelectedIDs()[0];
            int ticketSrcId = -1;
            switch((int) selId) {
                case InteractionHelper.INC_CALL_SRC:
                case InteractionHelper.OUT_CALL_SRC:
                    ticketSrcId = TicketHelper.PHONE_SRC;
                    break;
                case InteractionHelper.INC_EMAIL_SRC:
                case InteractionHelper.OUT_EMAIL_SRC:
                    ticketSrcId = TicketHelper.EMAIL_SRC;
                    break;
                case InteractionHelper.FAX_SRC:
                    ticketSrcId = TicketHelper.FAX_SRC;
                    break;
                case InteractionHelper.WALK_UP_SRC:
                    ticketSrcId = TicketHelper.WALK_UP_SRC;
                    break;
                default:
                    ticketSrcId = TicketHelper.OTHER_SRC;
            }
            long[] srcId = {ticketSrcId};
            clonedSource = new ListboxFieldData(TICKET_SOURCE_FIELD,
                    new SubsetData(srcId));
            //clonedSource.setFieldID(TICKET_SOURCE_FIELD);
        }

        if(!interAgent.isEmpty()) {
            clonedAgent = interAgent.cloneData();
            clonedAgent.setFieldID(TICKET_AGENT_ID_FIELD);
        }
        if(!interSubject.isEmpty()) {
            clonedSubject = interSubject.cloneData();
            clonedSubject.setFieldID(TICKET_SUBJECT_FIELD);
        }
        if(!interDescription.isEmpty()) {
            clonedDescription = interDescription.cloneData();
            clonedDescription.setFieldID(TICKET_DESCRIPTION_FIELD);
        }

        FieldData[] initData = new FieldData[6];
        initData[0] = clonedInterId;
        initData[1] = clonedSource;
        initData[2] = clonedInitiator;
        initData[3] = clonedAgent;
        initData[4] = clonedSubject;
        initData[5] = clonedDescription;
        return initData;
    }
    
    private void createTicketFromNewState(FamgMeta.Index formIndex) {
        FormOperations context = getOperationContext().getFormOperations();

        ticketHandler.setInitialFieldsData(createInitData(context, formIndex));
        OperationsHelper.createNewRecord(ticketFormId, getOperationContext());
    }

    public void setTicketHandler(TicketHandler ticketHandler) {
        this.ticketHandler = ticketHandler;
    }

    public void setTicketFormId(String ticketFormId) {
        this.ticketFormId = ticketFormId;
    }
}
