/*
 * 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.core.client.frames.email;

import com.google.gwt.user.client.ui.Widget;
import com.jpavel.gwt.wysiwyg.client.EditorUtils;
import com.queplix.core.client.app.rpc.RPC;
import com.queplix.core.client.app.vo.EmailComposeRequestObject;
import com.queplix.core.client.app.vo.EmailComposeResponseObject;
import com.queplix.core.client.common.StringUtil;
import com.queplix.core.client.common.event.Event;
import com.queplix.core.client.common.ui.ButtonData;
import com.queplix.core.client.common.ui.DialogAnswerListener;
import com.queplix.core.client.common.ui.DialogHelper;
import com.queplix.core.client.common.ui.OkayCancelPopup;

import java.util.HashMap;

/**
 * @author Alexander Melnik
 * @since 12 Mar 2007
 */
public class EmailComposeDialog extends OkayCancelPopup {
    private EmailComposeFrame emailComposeFrame;

    public EmailComposeDialog(String userEmail) {
        super(EmailComposeHelper.DIALOG_CAPTION, true);
        emailComposeFrame = new EmailComposeFrame(userEmail);
        boolean hideWhileResizing = EditorUtils.isGecko() ? true:false;
        setWidget(emailComposeFrame,
                ButtonData.SEND_MAIL | ButtonData.CANCEL_MAIL,
                hideWhileResizing);
        emailComposeFrame.setOffsetWidth(EmailComposeFrame.MIN_WIDTH);
        emailComposeFrame.setOffsetHeight(EmailComposeFrame.MIN_HEIGHT);
    }

    public EmailComposeDialog(String caption, boolean isFromEnabled,
                              boolean isSubjectEnabled) {
        super(caption, true);
        emailComposeFrame = new EmailComposeFrame(isFromEnabled,
                isSubjectEnabled);
        setWidget(emailComposeFrame,
                ButtonData.SEND_MAIL | ButtonData.CANCEL_MAIL);
        emailComposeFrame.setOffsetWidth(EmailComposeFrame.MIN_WIDTH);
        emailComposeFrame.setOffsetHeight(EmailComposeFrame.MIN_HEIGHT);
    }

    public void show() {
        show(false);
    }

    private void prepareToShow() {
        if(EditorUtils.isGecko()) {
            emailComposeFrame.initMemo();
        }
    }

    public void show(boolean isInitData) {
        prepareToShow();
        super.show();
        if(isInitData) {
            emailComposeFrame.setInitialData();
        } else {
            emailComposeFrame.resetInput();
        }
    }

    public void show(int left, int top) {
        prepareToShow();
        super.show(left, top);
        emailComposeFrame.resetInput();
    }

    public void show(Widget nextTo) {
        prepareToShow();
        super.show(nextTo);
        emailComposeFrame.resetInput();
    }

    public void setInitialDataMap(HashMap initMap) {
        emailComposeFrame.setInitialMap(initMap);
    }

    public void performSendEmailAction(EmailComposeRequestObject request,
                                       RPC.QAsyncCallback callback) {
        RPC.getRPC().sendEmail(request, callback);
    }

    public void onEvent(Event event, Widget sender) {
        if(event == OkayCancelPopup.Events.SEND) {
            if(emailComposeFrame.validate()) {
                String to = emailComposeFrame.getTo();
                String from = emailComposeFrame.getFrom();
                String cc = emailComposeFrame.getCc();
                String subject = emailComposeFrame.getSubject();
                String body = emailComposeFrame.getEmailBody(
                        processPlainTextAsHtml());
                long process_id = emailComposeFrame.getProcess_id();

                EmailComposeRequestObject request
                        = new EmailComposeRequestObject(process_id, to, from,
                        subject, body);
                request.setCc(cc);

                RPC.QAsyncCallback callback = new SendEmailAsyncCallack();
                performSendEmailAction(request, callback);
                hide();
            }
        } else if(event == OkayCancelPopup.Events.CANCEL) {
            String emailBody = StringUtil.nullToEmpty(
                    emailComposeFrame.getEmailBody(processPlainTextAsHtml()))
                    .trim();
            if(!emailBody.equals("") && !emailBody.equalsIgnoreCase("<br>")) {
                DialogHelper.showQuestionDialog(
                        EmailComposeHelper.EXIT_CONFIRMATION_MSG,
                        DialogHelper.YES | DialogHelper.NO,
                        cancelDialogListener,
                        DialogHelper.NO);
            } else {
                hide();
            }
        }
    }

    private DialogAnswerListener cancelDialogListener
            = new DialogAnswerListener() {
        public void anserIs(int answer) {
            if(answer == DialogHelper.YES) {
                hide();
            }
        }
    };

    private class SendEmailAsyncCallack extends RPC.QAsyncCallback {
        public void onRequestEnded(boolean success, Object result) {
            boolean wasSent = ((EmailComposeResponseObject) result).isResult();
            if(!wasSent) {
                DialogHelper.showMessageDialog(
                        EmailComposeHelper.EMAIL_SEND_FAILED);
            }
        }
    }

    public boolean processPlainTextAsHtml() {
        return false;
    }

}
