/*
 * 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.controls.memo;

import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HasVerticalAlignment;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import com.jpavel.gwt.wysiwyg.client.EditorUtils;
import com.queplix.core.client.app.vo.MemoFieldMeta;
import com.queplix.core.client.app.vo.uisettings.DialogUISettings;
import com.queplix.core.client.common.StringUtil;
import com.queplix.core.client.common.event.Event;
import com.queplix.core.client.common.event.EventListener;
import com.queplix.core.client.common.ui.ButtonData;
import com.queplix.core.client.common.ui.DialogHelper;
import com.queplix.core.client.common.ui.IconButton;
import com.queplix.core.client.common.ui.OkayCancelPopup;
import com.queplix.core.client.common.ui.resizable.Resizable;
import com.queplix.core.client.common.ui.resizable.ResizableScrollPanel;
import com.queplix.core.client.frames.htmledit.HtmlEditFrame;

/**
 * Memo contol popup view variant implementation.
 *
 * @author: Vasily Mikhailitchenko
 * @since: 15 Sep 2006
 */
class QMemoViewImplPopup extends QMemoViewImpl
        implements ClickListener, EventListener {
    private static final ButtonData EMPTY_STATE = new ButtonData(null, "Empty",
            QMemo.BUTTON_EMPTY_IMAGE_PATH);
    private static final ButtonData FILLED_STATE = new ButtonData(null,
            "Filled", QMemo.BUTTON_FULL_IMAGE_PATH);

    private final static int VIEW_DEFAULT_WIDTH = 600;
    private final static int VIEW_DEFAULT_HEIGHT = 400;
    private final static int VIEW_MIN_WIDTH = 100;
    private final static int VIEW_MIN_HEIGHT = 100;
    private OkayCancelPopup viewDialog;

    private static final QMemoEvent showEvent = new QMemoEvent(
            QMemoEvent.EVENT_SHOWPOPUP);
    private static final QMemoEvent cancelEvent = new QMemoEvent(
            QMemoEvent.EVENT_CANCEL);

    private static final String DISCARD_CONFIRMATION_MESSAGE
            = "Do you want to save the changes?";

    private static final String _EDITOR = " : Editor";

    private IconButton showbutton;

    private OkayCancelPopup searchDialog;

    private OkayCancelPopup htmlEditorDialog;
    private boolean htmlEditorDialogIsVisible = false;

    public QMemoViewImplPopup(QMemoModelImpl model, int layout) {
        super(model, layout);
    }

    public void onModelMetaChanged() {
        super.onModelMetaChanged();
        setupDialogTitles();
    }

    private void initGUIVisible() {
        // Actual visible part
        showbutton = new IconButton(getButtonState());
        addToLabelPanel(showbutton);
        addToLabelPanel(emptyButton);
        initPanel();
    }

    public void setText(String text) {
        super.setText(text);
        showbutton.setButtonState(getButtonState());
    }

    private ButtonData getButtonState() {
        String text = model.getData().getText();
        boolean empty = StringUtil.nullToEmpty(text).length() == 0;
        return empty ? EMPTY_STATE:FILLED_STATE;
    }

    public void setupDialogTitles() {
        String prefix = model.getMeta().getPrefixCaption();
        long pkey = model.getData().getRecordId();
        String caption = model.getMeta().getCaption();
        if(isEditMode() || isNewMode()) {
            htmlEditorDialog.setCaption(
                    prefix + " : " + pkey + " : " + caption + _EDITOR);
        }
        viewDialog.setCaption(prefix + " : " + pkey + " : " + caption);
        searchDialog.setCaption(caption + " : Text Search");
    }

    protected void initGUI() {
        super.initGUI();
        initGUIVisible();
        initGUIPopup();
        subscribeEvents();
    }

    private void initGUIPopup() {
        // The popup window
        viewDialog = new OkayCancelPopup("");
        viewDialog.addStyleName("memo");

        searchDialog = new OkayCancelPopup("");
        searchDialog.addStyleName("memo");

        MyVerticalPanel mvp = new MyVerticalPanel();
        mvp.add(textArea);

        searchDialog.setWidget(mvp);
        searchDialog.setUISettings(model.getMeta().getUISettings());

        ResizableScrollPanel rsp = new ResizableScrollPanel();
        rsp.setOffsetHeight(VIEW_DEFAULT_HEIGHT);
        rsp.setOffsetWidth(VIEW_DEFAULT_WIDTH);
        rsp.add(html);
        rsp.setStyleName("html_viewer");

        viewDialog.setWidget(rsp);
        viewDialog.setUISettings(model.getMeta().getUISettings());
        viewDialog.setMinSize(VIEW_MIN_WIDTH, VIEW_MIN_HEIGHT);

        if(!EditorUtils.isGecko()) {
            initIFrameDialog();
        }
    }

    private void initIFrameDialog() {
        htmlEditorDialog = new OkayCancelPopup("", true);
        htmlEditorDialogIsVisible = false;

        htmlEditorFrame.addEventListener(this);

        boolean hideWhileResizing = false;
        if(model.getMeta().getMemoType() == MemoFieldMeta.EDIT_TYPE) {
            hideWhileResizing = EditorUtils.isGecko() ? true:false;
        }
        htmlEditorDialog.setWidget(htmlEditorFrame,
                ButtonData.OK | ButtonData.CANCEL, hideWhileResizing);
        htmlEditorDialog.setUISettings(model.getMeta().getUISettings());
        htmlEditorDialog.getEventSource().addEventListener(this);

        setupDialogTitles();
    }

    public void showPopup() {
        switch(getControlType()) {
            case CONTROL_TEXTAREA:
                searchDialog.show(showbutton);
                refreshGUIData();
                break;
            case CONTROL_HTML_EDITOR:
                //workaround for FireFox (Firefox allows to edit HTML (designMode='on') on first popup show up only)
                if(EditorUtils.isGecko()) {
                    htmlEditorFrame = new HtmlEditFrame(model);
                    initIFrameDialog();
                }
                refreshGUIData();
                htmlEditorDialog.show(showbutton);
                htmlEditorFrame.setupEditor(StringUtil.nullToEmpty(
                        model.getData().getText()));
                htmlEditorDialogIsVisible = true;
                break;
            case CONTROL_HTML_VIEWER:
                viewDialog.show(showbutton);
                refreshGUIData();
                break;
        }
        setupDialogTitles();
    }

    public void removeEventHandler(QMemoEventHandler handler) {
        eventHandlers.remove(handler);
    }

    private void subscribeEvents() {
        showbutton.addClickListener(this);
        viewDialog.getEventSource().addEventListener(this);
        searchDialog.getEventSource().addEventListener(this);
    }

    public void onClick(Widget sender) {
        if(sender == showbutton) {
            eventHandlers.handleEvent(showEvent);
        }
    }

    public void setWidth(String width) {
        panel.setWidth(width);
    }

    public void onEvent(Event event, Widget sender) {
        if(event == OkayCancelPopup.Events.OK) {
            processOKEvent();
        } else if(event == OkayCancelPopup.Events.CANCEL) {
            if(htmlEditorDialogIsVisible) {
                String text = htmlEditorFrame.getHTML().trim();
                if(!text.equals("") && !text.equals("<br>") && !text.equals(
                        model.getData().getText()) &&
                        DialogHelper.showModalQuestionDialog(
                                DISCARD_CONFIRMATION_MESSAGE) == DialogHelper
                                .YES) {
                    processOKEvent();
                    return;
                }
                htmlEditorFrame.setText("");
                htmlEditorDialog.hide();
                htmlEditorDialogIsVisible = false;
            }
            eventHandlers.handleEvent(cancelEvent);
        }
    }

    private void processOKEvent() {
        if(htmlEditorDialogIsVisible) {
            String text = htmlEditorFrame.getText();
            htmlEditorFrame.resetEditor();
            if(htmlEditorFrame.isShowFrame()) {
                text = StringUtil.nullToEmpty(text);
                if(!text.equals("") && !HtmlEditFrame.isHTML(text)) {
                    text += HtmlEditFrame.HTML_INDICATOR;
                }
            } else {
                text = text.replaceAll(HtmlEditFrame.HTML_INDICATOR, "");
            }
            textArea.setText(text);
            htmlEditorDialog.hide();
            htmlEditorDialogIsVisible = false;
        }
        eventHandlers.handleEvent(saveEvent);
    }

    protected int getButtonWidth() {
        return showbutton.getOffsetWidth() + emptyButton.getOffsetWidth() - 1;
    }

    protected DialogUISettings getUISettings() {
        DialogUISettings htmlSettings = htmlEditorDialog.getUISettings();
        DialogUISettings searchSettings = searchDialog.getUISettings();
        DialogUISettings viewSettings = viewDialog.getUISettings();

        if(htmlSettings != null) {
            return htmlSettings;
        } else if(searchSettings != null) {
            return searchSettings;
        } else if(viewSettings != null) {
            return viewSettings;
        }
        return null;
    }

    protected void setEnabled(boolean isEnabled) {
    }

    protected void onModeChanged(int newMode) {
        showbutton.setEnabled(newMode != MODE_REPORT_DESIGN);
    }

    private class MyVerticalPanel extends VerticalPanel implements Resizable {
        public void setHorizontalAlignment(
                HasHorizontalAlignment.HorizontalAlignmentConstant align) {
        }

        public void setVerticalAlignment(
                HasVerticalAlignment.VerticalAlignmentConstant align) {
        }

        public void setOffsetHeight(int height) {
            textArea.setHeight(height + "px");
        }

        public void setOffsetWidth(int width) {
            textArea.setWidth(width + "px");
        }
    }

}
