/*
 * 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.EntityReferenceData;
import com.queplix.core.client.app.vo.EntityReferenceDataRequest;
import com.queplix.core.client.app.vo.FamgMeta;
import com.queplix.core.client.app.vo.FieldData;
import com.queplix.core.client.app.vo.FieldDataRequest;
import com.queplix.core.client.app.vo.RowData;
import com.queplix.core.client.app.vo.TextboxFieldData;
import com.queplix.core.client.common.ui.DialogHelper;
import com.queplix.core.client.frames.mainframe.FormOperations;
import com.queplix.core.client.frames.mainframe.FormState;
import java.util.Collection;

/**
 * Description:
 *
 * @author sergei.savchuk
 */
public class SolutionHandler extends OSSOperationStrategy {

    public static final String ATTACH_FILE = "ATTACH_FILE";
    public static final String SOLUTION_ID = "qw_solutionid";
    public static final String SUB_CATEGORY_FIELD_NAME = "qw_subcategoryid";
    public static final String CATEGORY_FIELD_NAME = "qw_categoryid";

    private static final String CUR_TICKET_ID_FIELD = "qw_cur_ticket";
    //private static final String TICKET_ID_FIELD = "qw_ticketid";

    private static final String ATTACHMENT_OBJECTS_ENTITY
            = "attachment_objects.solution";
    private static final String OBJECT_ID = "object_id";

    private static final String TICKET_ENTITY = "ticket.ticket";
    private static final String TICKET_FILTER_FIELD = "qw_solution";

    private FieldData[] initialFieldsData = null;
    private String curOriginTicketId = "0";

    /*
     * Ticket and AttachmentKnowledgeBase form ids
     * It should initialized in HandlerFactory or it's siblings
     */
    private String ticketFormId, attachKnowBaseFormId;

    // Ties with other handlers
    private TicketHandler ticketHandler;
    private AttachmentSolutionHandler attachSolutionHandler;

    protected boolean processControlDataRequest(FieldDataRequest request) {
        FamgMeta.Index formIndex = getFormIndex();
        String elementID = request.getElementID();
        FormOperations context = getOperationContext().getFormOperations();
        if(TicketHandler.COMPONENT_ID_FIELD_NAME.equalsIgnoreCase(elementID)) {
            EntityReferenceDataRequest theRequest
                    = (EntityReferenceDataRequest) request;
            FieldData productData = context.getFieldData(formIndex,
                    TicketHandler.PRODUCT_ID_FIELD_NAME);
            FieldData cloned = productData.cloneData();
            cloned.setFieldID(TicketHandler.COMPONENT_FILTER_FIELD_NAME);
            theRequest.setAdditionalFilterForRequestingEntity(cloned);
        } else if(SUB_CATEGORY_FIELD_NAME.equalsIgnoreCase(elementID)) {
            EntityReferenceDataRequest theRequest
                    = (EntityReferenceDataRequest) request;
            FieldData productData = context.getFieldData(formIndex,
                    CATEGORY_FIELD_NAME);
            FieldData cloned = productData.cloneData();
            cloned.setFieldID(CATEGORY_FIELD_NAME);
            theRequest.setAdditionalFilterForRequestingEntity(cloned);
        }
        return super.processControlDataRequest(request);
    }

    public void handleCustomButtonEvent(String buttonId) {
        FamgMeta.Index formIndex = getFormIndex();
        if(buttonId.equals(ATTACH_FILE)) {
            int state = getOperationContext().getFormOperations().getFormState(
                    formIndex);
            switch(state) {
                case FormState.SELECTED_STATE:
                    createNewAttachment(formIndex);
                    break;
                default:
                    DialogHelper.showModalMessageDialog(
                            "This button is available only in SELECTED state.");
            }
        }
    }

    private void createNewAttachment(FamgMeta.Index form) {
        FieldData solutionId = getOperationContext().getFormOperations()
                .getFieldData(
                        form, SOLUTION_ID);
        FieldData clonedSolutionId = solutionId.cloneData();
        FieldData[] initData = new FieldData[6];
        initData[0] = clonedSolutionId;

        attachSolutionHandler.setInitialFieldsData(initData);

        OperationsHelper.createNewRecord(attachKnowBaseFormId,
                getOperationContext());
    }
    
    protected boolean processFilteredLink(String linkedForm, 
            FormOperations formContext, FamgMeta.Index formIndex){
        EntityData linkFilter;
        if(linkedForm.equalsIgnoreCase( ticketFormId)) { // the link for ticket form is pressed
            //set filter
            EntityReferenceData erd = new EntityReferenceData(TICKET_FILTER_FIELD);
            erd.setSelectedRowID(formContext.getSelectedRecordId(formIndex));
            linkFilter = new EntityData(TICKET_ENTITY, new Long(-1), new FieldData[]{erd});
            ticketHandler.addExternalFilter(linkFilter);
            return CONTINUE;
        }    
        if(linkedForm.equalsIgnoreCase(attachKnowBaseFormId)) {
            linkFilter = new EntityData(ATTACHMENT_OBJECTS_ENTITY, new Long(-1), new FieldData[]{ 
                            new TextboxFieldData(OBJECT_ID, 
                                    formContext.getSelectedRecordId( formIndex).toString() ) });
            attachSolutionHandler.addExternalFilter(linkFilter);
            return CONTINUE;
        } 
        return BREAK;
    }
    
    public void setInitialFieldsData(FieldData[] fieldsData) {
        initialFieldsData = fieldsData;
    }

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

        FamgMeta.Index formIndex = getFormIndex();

        if(initialFieldsData != null && initialFieldsData.length > 0) {
            FormOperations formContext = getOperationContext()
                    .getFormOperations();
            for(int i = 0; i < initialFieldsData.length; i++) {
                if(initialFieldsData[i] != null) {
                    formContext.setFieldData(formIndex, initialFieldsData[i]);
                }
            }
            TextboxFieldData fieldData = (TextboxFieldData) formContext
                    .getFieldData(
                            formIndex, CUR_TICKET_ID_FIELD);
            String originTicketId = fieldData.getText();
            curOriginTicketId = (originTicketId != null) ? originTicketId:"0";
            initialFieldsData = null;
        } else {
            curOriginTicketId = "0";
        }
    }

    protected void insertRecordResponse(boolean success,
                                        EntityData[] entitiesList,
                                        EntityData[] externalFieldsList,
                                        Collection gridData, RowData updatedRow
    ) {

        super.insertRecordResponse(success, entitiesList, externalFieldsList,
                gridData, updatedRow);
        if(!success) {
            return;
        }
        if(!curOriginTicketId.equals("0")) {
            FormOperations formContext = getOperationContext()
                    .getFormOperations();
            long solutionId = formContext.getSelectedRecordId(getFormIndex())
                    .longValue();
            DialogHelper.showModalMessageDialog("The solution # " + solutionId
                    + " is assigned to ticket # " + curOriginTicketId + ".");

            curOriginTicketId = "0";
        }
    }

    public void setTicketHandler(TicketHandler ticketHandler) {
        this.ticketHandler = ticketHandler;
    }
    public TicketHandler getTicketHandler(){
        return ticketHandler;
    }
    
    public void setAttachSolutionHandler( AttachmentSolutionHandler attachSolutionHandler) {
        this.attachSolutionHandler = attachSolutionHandler;
    }
    public AttachmentSolutionHandler getAttachSolutionHandler(){
        return attachSolutionHandler;
    }

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

    public void setAttachKnowBaseFormId(String attachKnowBaseFormId) {
        this.attachKnowBaseFormId = attachKnowBaseFormId;
    }
    public String getAttachKnowBaseFormId() {
        return attachKnowBaseFormId;
    }
    
}
