/*
 * 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.google.gwt.user.client.ui.Widget;
import com.queplix.core.client.app.rpc.RPC;
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.GridSearchProperties;
import com.queplix.core.client.app.vo.TextboxFieldData;
import com.queplix.core.client.common.event.Event;
import com.queplix.core.client.common.ui.DialogHelper;
import com.queplix.core.client.common.ui.OkayCancelPopup;
import com.queplix.core.client.common.ui.WindowHelper;
import com.queplix.core.client.common.ui.upload.QFileUpload;
import com.queplix.core.client.common.ui.upload.QFileUploadListener;
import com.queplix.core.client.frames.mainframe.DefaultOperationStrategy;
import com.queplix.core.client.frames.mainframe.FormOperations;
import com.queplix.core.client.frames.mainframe.FormState;
import com.queplix.core.client.frames.mainframe.OperationTypes;
import com.queplix.qwoss.client.app.rpc.CustomRPC;

import java.util.ArrayList;
import java.util.Collection;

/**
 * Description:
 *
 * @author sergei.savchuk
 */
public abstract class AttachmentHandler extends OSSOperationStrategy
        implements QFileUploadListener {
    protected static final String ATTACHMENT_BUTTON = "ATTACHMENT_BUTTON";
    protected static final String VIEW_BUTTON = "VIEW_BUTTON";
    protected static final String LINK_TO_SOLUTION = "LINK_TO_SOLUTION";
    protected static final String LINK_TO_TICKET = "LINK_TO_TICKET";
    public static final String FILE_NAME = "filename";
    public static final String PROCESS_ID = "process_id";
    //public static final String SERVER_FILE_NAME = "server_filename";
    public static final String FILE_EXT = "fileext";
    public static final String DESCRIPTION_FIELD = "description";
    public static final String WIN_DELIMITER = "\\";
    public static final String UNX_DELIMITER = "/";
    private static final String EMPTY = "";

    private OkayCancelPopup popup;
    private QFileUpload fileUploadWiget;
    private FieldData[] initialFieldsData;

    public void handleCustomButtonEvent(String buttonId) {
        FamgMeta.Index formIndex = getFormIndex();
        FormOperations context = getOperationContext().getFormOperations();
        int state = context.getFormState(formIndex);
        if(buttonId.equalsIgnoreCase(ATTACHMENT_BUTTON)) {
            switch(state) {
                case FormState.NEW_STATE:
                case FormState.EDIT_STATE:
                    TextboxFieldData procIdTF = (TextboxFieldData) context
                            .getFieldData(formIndex, PROCESS_ID);
                    String action =
                            "../attachmentUpload/saveTemp?purge=1&process_id="
                                    + procIdTF.getText();
                    fileUploadWiget = new QFileUpload(action);
                    //fileUploadWiget = new QFileUpload("../fileUpload/attach");
                    fileUploadWiget.addQFileUploadListener(this);
                    popup = new OkayCancelPopup("Attach File:", true) {
                        public void onEvent(Event event, Widget sender) {
                            if(OkayCancelPopup.Events.OK == event) {
                                fileUploadWiget.submitUpload();
                            } else if(OkayCancelPopup.Events.CANCEL == event) {
                                popup.hide();
                            }
                        }
                    };
                    fileUploadWiget.setUploadButtonVisible(false);
                    popup.setWidget(fileUploadWiget);
                    popup.show();
                    break;
            }
        } else if(buttonId.equalsIgnoreCase(VIEW_BUTTON)) {
            switch(state) {
                case FormState.SELECTED_STATE:
                    viewAttachment(formIndex);
                    break;
                default:
                    DialogHelper.showModalMessageDialog(
                            "This button is available only in SELECTED state.");
            }
        }
    }


    private void viewAttachment(FamgMeta.Index form) {
        Long fileId = getOperationContext().getFormOperations()
                .getSelectedRecordId(form);
        //String url = "../fileUpload/getAttach?id=" + fileId;
        String url = "../attachmentUpload/get?id=" + fileId;
        WindowHelper.openWindow(url);
    }


    public void onFileUploaded(Widget sender, String fileName) {
        FamgMeta.Index formIndex = getFormIndex();
        String localFileName = fileUploadWiget.getFileUploadName();
        String delimeter = obtainDelimiter(fileName),
                localDelimiter = obtainDelimiter(localFileName);
        
        FormOperations context = getOperationContext().getFormOperations();

        //TextboxFieldData serverFileNameTF = (TextboxFieldData) context.getFieldData(
        //        formIndex, SERVER_FILE_NAME);

        String extractedFileName = extractFileName(localFileName,
                localDelimiter) + '.' + extractFileExt(localFileName);
        
        //TextboxFieldData fileNameTF = (TextboxFieldData) context.getFieldData(
        //        formIndex, FILE_NAME);
        //TextboxFieldData fileExtTF = (TextboxFieldData) context.getFieldData(
        //        formIndex, FILE_EXT);
        //TextboxFieldData descriptionTF = (TextboxFieldData) context.getFieldData(
        //        formIndex, DESCRIPTION_FIELD);
        
        //fileNameTF.setText(extractedFileName);
        //if(descriptionTF.isEmpty()) 
        //    descriptionTF.setText(extractedFileName);
        //fileExtTF.setText(extractFileExt(localFileName));
        
        TextboxFieldData fileNameTF = new TextboxFieldData(FILE_NAME, extractedFileName);
        context.setFieldData(formIndex, fileNameTF);
        TextboxFieldData fileExtTF = new TextboxFieldData(FILE_EXT, extractFileExt(localFileName));
        context.setFieldData(formIndex, fileExtTF);
        if(context.getFieldData(formIndex, DESCRIPTION_FIELD).isEmpty()){
            TextboxFieldData descriptionTF = new TextboxFieldData(DESCRIPTION_FIELD, extractedFileName);
            context.setFieldData(formIndex, descriptionTF);
        }
            
        //serverFileNameTF.setText(extractFileName(fileName, delimeter));
        //procIdTF.setText(processId+"");
        //processId = -1; 
        //context.setFieldData(formIndex, serverFileNameTF);
        //context.setFieldData(formIndex, procIdTF);
        popup.hide();
    }

    private String extractFileName(String fullname, String delimiter) {
        int pos = fullname.lastIndexOf(".");
        return fullname.substring(fullname.lastIndexOf(delimiter) + 1,
                pos != -1 ? pos:fullname.length());
    }

    private String extractFileExt(String fileName) {
        int pos = fileName.lastIndexOf(".");
        if(pos != -1) {
            return fileName.substring(pos + 1);
        }
        return EMPTY;
    }

    private String obtainDelimiter(String fileName) {
        return fileName.indexOf(UNX_DELIMITER) == -1 ? WIN_DELIMITER
                :UNX_DELIMITER;
    }

    public void setInitialFieldsData(FieldData[] fieldsData) {
        initialFieldsData = fieldsData;
    }

    protected void createRecordProtorypeResponse(boolean success,
                                                 FieldData[] fields,
                                                 Long rowId) {
        super.createRecordProtorypeResponse(success, fields, rowId);
        if(!success) {
            return;
        }
        FormOperations context = getOperationContext().getFormOperations();
        if(initialFieldsData != null && initialFieldsData.length > 0) {
            FamgMeta.Index formIndex = getFormIndex();
            for(int i = 0; i < initialFieldsData.length; i++) {
                if(initialFieldsData[i] != null) {
                    context.setFieldData(
                            formIndex, initialFieldsData[i]);
                }
            }
            initialFieldsData = null;
        }
        TextboxFieldData procIdTF = (TextboxFieldData) context.getFieldData(
                getFormIndex(), PROCESS_ID);
        procIdTF.setText(System.currentTimeMillis() + "");
        context.setFieldData(getFormIndex(), procIdTF);
    }

    public void deleteRecord(Collection rowIds) {
        FamgMeta.Index formIndex = getFormIndex();
        DeleteAttachmentAsyncCallback callback
                = new DeleteAttachmentAsyncCallback(formIndex);
        CustomRPC.getCustomRPC().deleteAttachment(rowIds, callback);
    }

    protected class CreateLinkAsyncCallback extends RPC.QAsyncCallback {
        public CreateLinkAsyncCallback() {
        }

        public void onRequestEnded(boolean success, Object result) {
            if(success) {
                Boolean rv = (Boolean) result;
                if(!rv.booleanValue()) {
                    DialogHelper.showModalMessageDialog(
                            "The link already exists.");
                } else {
                    DialogHelper.showModalMessageDialog("The link is created.");
                }
            } else {
                DialogHelper.showModalMessageDialog("RPC call failed.");
            }
        }
    }

    protected class DeleteAttachmentAsyncCallback extends RPC.QAsyncCallback {
        private FamgMeta.Index form;

        public DeleteAttachmentAsyncCallback(FamgMeta.Index form) {
            this.form = form;
        }

        public void onRequestEnded(boolean success, Object result) {
            if(success) {
                DialogHelper.showModalMessageDialog("Record was deleted");
                FormOperations context = getOperationContext()
                        .getFormOperations();
                context.turnFormToState(form, FormState.SEARCH_STATE);
                context.clearForm(form, false);
                getOperationContext().performOperation(
                        OperationTypes.SEARCH_RECORDS, getFormIndex());
                //todo check, if that is what we wanted to do
            } else {
                DialogHelper.showModalMessageDialog("RPC call failed.");
            }
        }
    }
}
