/*
 * 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;

import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.ui.AbsolutePanel;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HasVerticalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.KeyboardListenerAdapter;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
import com.queplix.core.client.common.StringUtil;
import com.queplix.core.client.common.event.Event;
import com.queplix.core.client.common.event.EventSource;
import com.queplix.core.client.i18n.I18N;

/**
 * Login Frame.
 *
 * @author Sultan Tezadov, Vasily Mikhailitchenko
 * @since 24 Sep 2006
 */
// TODO: once generics enabled, remove all occurences of '/*]' and '[*/'
public class LoginFrame extends AbsolutePanel implements ClickListener, QFrame {

    private static final String CSS_PREFIX = "login_";

    private static final String PRIVACY_URL
            = "http://www.queplix.com/privacy-statement/";
    private static final String IMAGE_BUTTON = "loginframe/button_login.gif";
    private static final String BUTTON_HEIGHT = "25px";
    private static final String BUTTON_WIDTH = "104px";
    private static final String IMAGE_LOADING = "loginframe/loading.gif";
    private static final String IMAGE_HEIGHT = "16px";
    private static final String IMAGE_WIDTH = "16px";

    // -------------------- public events ------------------------
    public static interface Events {
        /**
         * Login event.
         * Event data passed along with it is of type LoginFrame.LoginEventData
         */
        Event/*]<LoginEventData>[*/ LOGIN = new Event/*]<LoginEventData>[*/();
    }

    public static class LoginEventData {
        public String login;
        public String password;
        private String portalType;

        public String getPortalType() {
            return portalType;
        }

        public void setPortalType(String portalType) {
            this.portalType = portalType;
        }
    }

    private EventSource eventSource = new EventSource(this);

    public EventSource getEventSource() {
        return eventSource;
    }
    // ----------------- end of public events --------------------

    private TextBox login;
    private PasswordTextBox password;
    private Image submit;
    private Label message;
    private String portalType;

    public LoginFrame(boolean isMozilla, String portalType) {
        
        login = new TextBox();
        password = new PasswordTextBox();
        submit = new Image(IMAGE_BUTTON);
        message = new Label();

        String privacyText = "<a href='" + PRIVACY_URL + "' target='_blank'>"
                + I18N.getMessages().privacyStatement() + "</a>";

        AbsolutePanel mainPanel = new AbsolutePanel();
        AbsolutePanel mainArea = new AbsolutePanel();
        AbsolutePanel formPanel = new AbsolutePanel();
        HorizontalPanel internalFormArea = new HorizontalPanel();
        Grid loginPasswordGrid = new Grid(3, 2);

        HTML topStripe = new HTML();
        HTML queplixLogo = new HTML();
        HTML quewebLogo = new HTML();
        HTML welcomeText = new HTML();
        HTML titleText = new HTML(I18N.getMessages().enterLoginAndPassword());
        HTML copyrightText = new HTML(
                I18N.getMessages().copyrightText() + "<br/>" + privacyText);
        Label loginCaption = new Label(I18N.getMessages().login());
        Label passwordCaption = new Label(I18N.getMessages().password());

        this.addStyleName(
                isMozilla ? CSS_PREFIX + "bottom_ff":CSS_PREFIX + "bottom_ie");
        login.addStyleName(CSS_PREFIX + "text_input");
        password.addStyleName(CSS_PREFIX + "text_input");
        submit.addStyleName(CSS_PREFIX + "button");

        topStripe.addStyleName(CSS_PREFIX + "top_stripe");
        mainArea.addStyleName(CSS_PREFIX + "main_area");
        queplixLogo.addStyleName(CSS_PREFIX + "queplix_logo");
        quewebLogo.addStyleName(CSS_PREFIX + "queweb_logo");
        welcomeText.addStyleName(CSS_PREFIX + "welcome_text");
        formPanel.addStyleName(CSS_PREFIX + "form");
        titleText.addStyleName(CSS_PREFIX + "titleText");
        loginCaption.addStyleName(CSS_PREFIX + "fields_captions");
        passwordCaption.addStyleName(CSS_PREFIX + "fields_captions");
        copyrightText.addStyleName(CSS_PREFIX + "copyrightText");
        internalFormArea.addStyleName(CSS_PREFIX + "internalFormArea");

        this.add(mainPanel);
        mainPanel.add(topStripe);
        mainPanel.add(mainArea);

        mainArea.add(queplixLogo);
        mainArea.add(welcomeText);
        mainArea.add(formPanel);
        mainArea.add(copyrightText);

        formPanel.add(titleText);
        formPanel.add(internalFormArea);

        internalFormArea.add(loginPasswordGrid);
        internalFormArea.add(quewebLogo);
        internalFormArea.setCellWidth(loginPasswordGrid, StringUtil.pixelToSize(
                264));
        internalFormArea.setCellVerticalAlignment(quewebLogo,
                HasVerticalAlignment.ALIGN_TOP);

        loginPasswordGrid.setCellPadding(5);
        loginPasswordGrid.setWidget(0, 0, loginCaption);
        loginPasswordGrid.setWidget(0, 1, login);
        loginPasswordGrid.setWidget(1, 0, passwordCaption);
        loginPasswordGrid.setWidget(1, 1, password);
        loginPasswordGrid.setWidget(2, 1, submit);
        loginPasswordGrid.getCellFormatter().setHorizontalAlignment(2, 1,
                HasHorizontalAlignment.ALIGN_RIGHT);

        KeyboardListenerAdapter enterPressedAdapter
                = new KeyboardListenerAdapter() {
            public void onKeyPress(Widget sender, char keyCode, int modifiers) {
                if(KeyboardListenerAdapter.KEY_ENTER == keyCode) {
                    doSubmit();
                }
            }
        };

        login.addKeyboardListener(enterPressedAdapter);
        password.addKeyboardListener(enterPressedAdapter);

        login.setTabIndex(100);
        password.setTabIndex(101);
        submit.addClickListener(this);
        this.setWidth("100%");

        DOM.setAttribute(this.getElement(), "id", "clickable");
    }

    // --- Temp method to speed-up login ---
    public void forceSubmit(String val) {
        login.setText(val);
        doSubmit();
    }

    public TextBox getLoginWidget() {
        return login;
    }

    private void doSubmit() {
        setLoginPageEnabled(false);
        LoginEventData eventData = new LoginEventData();
        eventData.login = login.getText();
        eventData.password = password.getText();
        eventData.portalType = portalType;
        Events.LOGIN.setData(eventData);
        eventSource.fireEvent(Events.LOGIN);
    }

    public void onClick(Widget sender) {
        doSubmit();
    }

    public void clearLoginPage(boolean flag) {
        login.setText("");
        password.setText("");
        message.setText("");
        setLoginPageEnabled(flag);
    }

    private void setSubmitEnabled(boolean flag) {
        if(flag) {
            submit.addClickListener(this);
            submit.setUrl(IMAGE_BUTTON);
            submit.setSize(BUTTON_WIDTH, BUTTON_HEIGHT);
        } else {
            submit.removeClickListener(this);
            submit.setUrl(IMAGE_LOADING);
            submit.setSize(IMAGE_WIDTH, IMAGE_HEIGHT);
        }
    }

    public void setLoginPageEnabled(boolean flag) {
        setSubmitEnabled(flag);
        login.setEnabled(flag);
        password.setEnabled(flag);
    }

    public void displaySuccessMessage() {
        message.setText(I18N.getMessages().loginSuccess());
    }

    public Widget getView() {
        return this;
    }

    public void activated() {
    }

    public void disabled() {
    }
}
