/**
 * Copyright (C) 2004-2011 Jive Software. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
 *
 * 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 org.jivesoftware.sparkimpl.preference.chat;

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.*;

import org.jivesoftware.resource.Default;
import org.jivesoftware.resource.Res;
import org.jivesoftware.spark.SparkManager;
import org.jivesoftware.spark.component.VerticalFlowLayout;
import org.jivesoftware.spark.util.ResourceUtils;
import org.jivesoftware.sparkimpl.plugin.manager.Enterprise;
import org.jivesoftware.sparkimpl.settings.local.LocalPreferences;
import org.jivesoftware.sparkimpl.settings.local.SettingsManager;

/**
 * The Preference UI used to handle changing of Chat Preferences.
 */
public class ChatPreferencePanel extends JPanel {
	private final JCheckBox showTimeBox = new JCheckBox();
    private final ButtonGroup timeFormat = new ButtonGroup();
    private final JRadioButton format12 = new JRadioButton("12:00 PM", false);
    private final JRadioButton format24 = new JRadioButton("24:00", true);
    private final JRadioButton format12s = new JRadioButton("12:00:00 PM", false);
    private final JRadioButton format24s = new JRadioButton("24:00:00", false);
    private final JCheckBox groupChatNotificationBox = new JCheckBox();
    private final JPanel chatWindowPanel = new JPanel();
    private final JCheckBox hideChatHistory = new JCheckBox();
    private final JCheckBox sortChatHistoryAscending = new JCheckBox();
    private final JCheckBox hidePrevChatHistory = new JCheckBox();
    private final JCheckBox tabsOnTopBox = new JCheckBox();
    private final JSpinner chatTimeoutField = new JSpinner(new SpinnerNumberModel(15, 1, 24*60, 1));
    private final JCheckBox buzzBox = new JCheckBox();
    private final JCheckBox closeUnreadMessageBox = new JCheckBox();
    private final JCheckBox tabsScrollBox = new JCheckBox();

    public ChatPreferencePanel() {
        // Build the UI
        createUI();
    }

    private void createUI() {
        setLayout(new VerticalFlowLayout());
        timeFormat.add(format24);
        timeFormat.add(format24s);
        timeFormat.add(format12);
        timeFormat.add(format12s);
        final LocalPreferences pref = SettingsManager.getLocalPreferences();
        switch (pref.getTimeFormat()) {
            case "HH:mm":
                format24.setSelected(true);
                break;
            case "HH:mm:ss":
                format24s.setSelected(true);
                break;
            case "h:mm a":
                format12.setSelected(true);
                break;
            default:
                format12s.setSelected(true);
                break;
        }
        
        // Setup Mnemonics
        ResourceUtils.resButton(showTimeBox, Res.getString("checkbox.show.time.in.chat.window"));
        ResourceUtils.resButton(groupChatNotificationBox, Res.getString("checkbox.show.notifications.in.conference"));
        ResourceUtils.resButton(hideChatHistory, Res.getString("checkbox.disable.chat.history"));
        ResourceUtils.resButton(hidePrevChatHistory, Res.getString("checkbox.disable.prev.chat.history"));
        ResourceUtils.resButton(sortChatHistoryAscending, Res.getString("checkbox.sort.asc.history"));
        ResourceUtils.resButton(tabsOnTopBox, Res.getString("checkbox.tabs.on.top"));
        ResourceUtils.resButton(tabsScrollBox, Res.getString("checkbox.tabs.scroll"));
        ResourceUtils.resButton(buzzBox, Res.getString("checkbox.allow.buzz"));
        ResourceUtils.resButton(closeUnreadMessageBox,Res.getString("checkbox.close.unread.message"));

        chatWindowPanel.setBorder(BorderFactory.createTitledBorder(Res.getString("group.chat.window.information")));

        add(chatWindowPanel);

        chatWindowPanel.setLayout(new GridBagLayout());

        // Chat Window Panel settings
        chatWindowPanel.add(showTimeBox, new GridBagConstraints(0, 0, 2, 1, 1.0, 1.0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
        chatWindowPanel.add(format24, new GridBagConstraints(1, 0, 2, 1, 1.0, 1.0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
        chatWindowPanel.add(format24s, new GridBagConstraints(1, 1, 2, 1, 1.0, 1.0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));        
        chatWindowPanel.add(format12, new GridBagConstraints(2, 0, 2, 1, 1.0, 1.0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
        chatWindowPanel.add(format12s, new GridBagConstraints(2, 1, 2, 1, 1.0, 1.0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));

        chatWindowPanel.add(groupChatNotificationBox, new GridBagConstraints(0, 2, 2, 1, 1.0, 1.0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));

        if (!Default.getBoolean(Default.HISTORY_DISABLED) && !Default.getBoolean(Default.HIDE_HISTORY_SETTINGS)
        		&& Enterprise.containsFeature(Enterprise.HISTORY_SETTINGS_FEATURE) && Enterprise.containsFeature(Enterprise.HISTORY_TRANSCRIPTS_FEATURE)) {
        	chatWindowPanel.add(hideChatHistory, new GridBagConstraints(0, 3, 2, 1, 1.0, 1.0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
        	chatWindowPanel.add(hidePrevChatHistory, new GridBagConstraints(0, 4, 2, 1, 1.0, 1.0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
        }

        chatWindowPanel.add(sortChatHistoryAscending, new GridBagConstraints(0, 5, 2, 1, 1.0, 1.0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
        chatWindowPanel.add(tabsOnTopBox, new GridBagConstraints(0, 6, 2, 1, 1.0, 1.0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
        chatWindowPanel.add(tabsScrollBox, new GridBagConstraints(0, 7, 2, 1, 1.0, 1.0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
        chatWindowPanel.add(buzzBox, new GridBagConstraints(0, 8, 2, 1, 1.0, 1.0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
        chatWindowPanel.add(closeUnreadMessageBox, new GridBagConstraints(0, 9, 2, 1, 1.0, 1.0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));

        JLabel chatTimeoutLabel = new JLabel();
        ResourceUtils.resLabel(chatTimeoutLabel, chatTimeoutField, Res.getString("label.minutes.before.stale.chat") + ":");
        chatWindowPanel.add(chatTimeoutLabel, new GridBagConstraints(0, 10, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
        chatWindowPanel.add(chatTimeoutField, new GridBagConstraints(1, 10, 2, 1, 1.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 50, 0));

        showTimeBox.addActionListener(e -> {
            format12.setEnabled(showTimeBox.isSelected());
            format24.setEnabled(showTimeBox.isSelected());
            format12s.setEnabled(showTimeBox.isSelected());
            format24s.setEnabled(showTimeBox.isSelected());
        });

        hideChatHistory.addActionListener(e -> this.hideChatHistoryEnabled());
    }

    public void setShowTime(boolean showTime) {
        showTimeBox.setSelected(showTime);
    }

    /**
     * Returns true if the ChatWindow should show a timestamp of each message.
     */
    public boolean getShowTime() {
        return showTimeBox.isSelected();
    }
    
    public String getFormatTime() {
       if(format24.isSelected())
       {
      	 return "HH:mm";
       }
       else if(format24s.isSelected())
       {
    	 return "HH:mm:ss";
       }
       else if(format12.isSelected())
       {
    	 return "h:mm a";
       }
       else
       {
      	 return "h:mm:ss a"; 
       }
    }

    public void setSortChatHistoryAscending(boolean on) {
        sortChatHistoryAscending.setSelected(on);
    }

    public boolean isSortChatHistoryAscending() {
        return sortChatHistoryAscending.isSelected();
    }

    public void setGroupChatNotificationsOn(boolean on) {
        groupChatNotificationBox.setSelected(on);
    }

    public boolean isGroupChatNotificationsOn() {
        return groupChatNotificationBox.isSelected();
    }

    public void setChatHistoryHidden(boolean hide) {
        hideChatHistory.setSelected(hide);
    }

    public boolean isChatHistoryHidden() {
        return hideChatHistory.isSelected();
    }

    public void setPrevChatHistoryHidden(boolean hide) {
        hidePrevChatHistory.setSelected(hide);
    }

    public boolean isPrevChatHistoryHidden() {
        return hidePrevChatHistory.isSelected();
    }

    public void setChatTimeoutTime(int time) {
        chatTimeoutField.setValue(time);
    }

    public void setTabsOnTop(boolean top) {
        tabsOnTopBox.setSelected(top);
    }

    public boolean isTabsOnTop() {
        return tabsOnTopBox.isSelected();
    }

    public void setTabsScrollBox(boolean top) {
        tabsScrollBox.setSelected(top);
    }

    public boolean isTabScroll() {
        return tabsScrollBox.isSelected();
    }

    public void setBuzzEnabled(boolean allowBuzz) {
        buzzBox.setSelected(allowBuzz);
    }

    public boolean isBuzzEnabled() {
        return buzzBox.isSelected();
    }

    public void setCloseUnreadMessageEnabled(boolean askBeforeClosing) {
        closeUnreadMessageBox.setSelected(askBeforeClosing);
    }

    public boolean isCloseUnreadMessageEnabled() {
        return closeUnreadMessageBox.isSelected();
    }

    public int getChatTimeoutTime() {
        return (int) chatTimeoutField.getValue();
    }

    public void hideChatHistoryEnabled() {
        if (hideChatHistory.isSelected()) {
            int ok = JOptionPane.showConfirmDialog(this, Res.getString("message.delete.all.history"), Res.getString("title.confirmation"), JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
            if (ok == JOptionPane.YES_OPTION) {
                hidePrevChatHistory.setEnabled(false);
                hidePrevChatHistory.setSelected(false);
                File[] files = SparkManager.getTranscriptDir().listFiles(File::isFile);
                files = files != null ? files : new File[0];
                for (File transcriptFile : files) {
                    transcriptFile.delete();
                }
            }
        } else {
            hidePrevChatHistory.setEnabled(true);
        }
    }
}
