/**
 * 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.plugin.transcripts;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.MouseEvent;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

import org.jivesoftware.MainWindowListener;
import org.jivesoftware.resource.Default;
import org.jivesoftware.resource.Res;
import org.jivesoftware.resource.SparkRes;
import org.jivesoftware.smack.ConnectionListener;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smackx.jiveproperties.packet.JivePropertiesExtension;

import org.jivesoftware.spark.SparkManager;
import org.jivesoftware.spark.plugin.ContextMenuListener;
import org.jivesoftware.spark.ui.ChatRoom;
import org.jivesoftware.spark.ui.ChatRoomButton;
import org.jivesoftware.spark.ui.ChatRoomClosingListener;
import org.jivesoftware.spark.ui.ChatRoomListener;
import org.jivesoftware.spark.ui.ContactItem;
import org.jivesoftware.spark.ui.ContactList;
import org.jivesoftware.spark.util.UIComponentRegistry;
import org.jivesoftware.sparkimpl.plugin.manager.Enterprise;
import org.jivesoftware.sparkimpl.settings.local.LocalPreferences;
import org.jivesoftware.sparkimpl.settings.local.SettingsManager;
import org.jxmpp.jid.*;

/**
 * The <code>ChatTranscriptPlugin</code> is responsible for transcript handling within Spark.
 * It registers the listeners for transcript persistence.
 *
 * @author Derek DeMoro
 */
public class ChatTranscriptPlugin implements ChatRoomListener {
    private final HashMap<EntityJid, Message> lastMessage = new HashMap<>();
    private JDialog Frame;
    private final LocalPreferences pref = SettingsManager.getLocalPreferences();

    public ChatTranscriptPlugin() {
        SparkManager.getChatManager().addChatRoomListener(this);
        final ContactList contactList = SparkManager.getWorkspace().getContactList();

        final Action viewHistoryAction = new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                ContactItem item = contactList.getSelectedUsers().get(0);
                EntityJid jid = item.getJid().asEntityBareJidIfPossible();
                if (jid == null) {
                    return;
                }
                showHistory(jid);
            }
        };

        viewHistoryAction.putValue(Action.NAME, Res.getString("menuitem.view.contact.history"));
        viewHistoryAction.putValue(Action.SMALL_ICON, SparkRes.getImageIcon(SparkRes.Icon.HISTORY_16x16));

        final Action showStatusMessageAction = new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                ContactItem item = contactList.getSelectedUsers().get(0);
                showStatusMessage(item);
            }
        };

        showStatusMessageAction.putValue(Action.NAME, Res.getString("menuitem.show.contact.statusmessage"));

        contactList.addContextMenuListener(new ContextMenuListener() {
            @Override
            public void poppingUp(Object object, JPopupMenu popup) {
                if (!(object instanceof ContactItem)) {
                    return;
                }
                if (isChatHistoryEnabled()) {
                    popup.add(viewHistoryAction);
                }
                popup.add(showStatusMessageAction);
            }

            @Override
            public boolean handleDefaultAction(MouseEvent e) {
                return false;
            }
        });

        SparkManager.getMainWindow().addMainWindowListener(new MainWindowListener() {
            @Override
            public void shutdown() {
                persistConversations();
            }
        });

        SparkManager.getConnection().addConnectionListener(new ConnectionListener() {
            @Override
            public void connectionClosedOnError(Exception e) {
                persistConversations();
            }
        });
    }

    public void persistConversations() {
        for (ChatRoom room : SparkManager.getChatManager().getChatContainer().getChatRooms()) {
                if (room.isActive()) {
                    persistChatRoom(room);
                }
        }
    }

    public boolean canShutDown() {
        return true;
    }

    @Override
    public void chatRoomOpened(final ChatRoom room) {
        if (!isChatHistoryEnabled()) {
            return;
        }
        final EntityBareJid jid = room.getBareJid();
        File transcriptFile = ChatTranscripts.getTranscriptFile(jid);
        if (!transcriptFile.exists()) {
            return;
        }
        new ChatRoomDecorator(room);
    }

    @Override
    public void chatRoomClosed(final ChatRoom room) {
        // Persist only agent to agent chat rooms.
        if (room.getChatType() == Message.Type.chat) {
            persistChatRoom(room);
        }
    }

    public void persistChatRoom(final ChatRoom room) {
        if (!isChatHistoryEnabled()) {
            return;
        }
        EntityJid jid = room.getJid();

        final List<Message> transcripts = room.getTranscripts();
        int count = 0;
        Message lastKnownMessage = lastMessage.get(jid);
        if (lastKnownMessage != null) {
            count = transcripts.indexOf(lastKnownMessage) + 1;
        }
        if (count == transcripts.size()) {
            return;
        }
        // Build transcript from messages after the last known message
        ChatTranscript transcript = new ChatTranscript();
        for (int j = count; j < transcripts.size(); j++) {
            Message message = transcripts.get(j);
            HistoryMessage history = new HistoryMessage();
            history.setTo(message.getTo());
            history.setFrom(message.getFrom());
            history.setBody(message.getBody());
            final JivePropertiesExtension extension = message.getExtension(JivePropertiesExtension.class);
            Date date = extension != null ? (Date) extension.getProperty("date") : new Date();
            history.setDate(date);
            transcript.addHistoryMessage(history);
        }
        Message newLastKnownMessage = transcripts.get(transcripts.size() - 1);
        lastMessage.put(jid, newLastKnownMessage);
        ChatTranscripts.appendToTranscript(jid, transcript);
    }

    private void showStatusMessage(ContactItem item) {
        Frame = new JDialog();
        Frame.setTitle(item.getDisplayName() + " - Status");
        JPanel pane = new JPanel();
        JTextArea textArea = new JTextArea(5, 30);
        JButton btn_close = new JButton(Res.getString("button.close"));

        btn_close.addActionListener(e -> Frame.setVisible(false));

        textArea.setLineWrap(true);
        textArea.setWrapStyleWord(true);

        pane.add(new JScrollPane(textArea));
        Frame.setLayout(new BorderLayout());
        Frame.add(pane, BorderLayout.CENTER);
        Frame.add(btn_close, BorderLayout.SOUTH);

        textArea.setEditable(false);
        textArea.setText(item.getStatus());

        Frame.setLocationRelativeTo(SparkManager.getMainWindow());
        Frame.setBounds(Frame.getX() - 175, Frame.getY() - 75, 350, 150);
        Frame.setSize(350, 150);
        Frame.setResizable(false);
        Frame.setVisible(true);
    }

    private boolean isChatHistoryEnabled() {
        return pref.isChatHistoryEnabled() && !Default.getBoolean(Default.HISTORY_DISABLED) && Enterprise.containsFeature(Enterprise.HISTORY_TRANSCRIPTS_FEATURE);
    }

    private static void showHistory(EntityJid jid) {
        String dateFormat = ((SimpleDateFormat) SimpleDateFormat.getDateInstance(SimpleDateFormat.FULL)).toPattern();
        SimpleDateFormat notificationDateFormatter = new SimpleDateFormat(dateFormat);
        SimpleDateFormat messageDateFormatter = new SimpleDateFormat("HH:mm:ss");
        HistoryTranscript transcript = new HistoryTranscript(notificationDateFormatter, messageDateFormatter);
        transcript.showHistory(jid);
    }

    private class ChatRoomDecorator implements ChatRoomClosingListener {
        private ChatRoom chatRoom;
        private ChatRoomButton chatHistoryButton;

        public ChatRoomDecorator(ChatRoom chatRoom) {
            this.chatRoom = chatRoom;
            chatRoom.addClosingListener(this);
            // Add History Button
            if (isChatHistoryEnabled()) {
                chatHistoryButton = UIComponentRegistry.getButtonFactory().createChatTranscriptButton();
                chatRoom.addChatRoomButton(chatHistoryButton);
                chatHistoryButton.setToolTipText(Res.getString("tooltip.view.history"));
                chatHistoryButton.addActionListener(e -> {
                    EntityJid jid = chatRoom.getJid();
                    showHistory(jid);
                });
            }
        }

        @Override
        public void closing() {
            chatRoom.removeClosingListener(this);
            chatRoom = null;
            chatHistoryButton = null;
        }

    }

}

