package kiyut.alkitab.windows;

import java.awt.BorderLayout;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.Serializable;
import java.net.URISyntaxException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JTabbedPane;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkEvent.EventType;
import javax.swing.event.HyperlinkListener;
import kiyut.alkitab.api.BookViewManager;
import kiyut.alkitab.api.SwordURI;
import kiyut.alkitab.swing.DictionaryPane;
import org.crosswire.jsword.book.Book;
import org.crosswire.jsword.book.Books;
import org.openide.awt.StatusDisplayer;
import org.openide.awt.TabbedPaneFactory;
import org.openide.util.NbBundle;
import org.openide.windows.TopComponent;
import org.openide.windows.WindowManager;
//import org.openide.util.Utilities;

/**
 * Top component which displays {@link kiyut.alkitab.swing.DictionaryPane DictionaryPane}.
 */
public final class DictionariesTopComponent extends TopComponent {

    private static DictionariesTopComponent instance;
    /** path to the icon used by the component and its open action */
//    static final String ICON_PATH = "SET/PATH/TO/ICON/HERE";

    private static final String PREFERRED_ID = "DictionariesTopComponent";
    
    private JTabbedPane tabbedPane;
    
    private HyperlinkListener hyperlinkListener;
    
    private DictionariesTopComponent() {
        initComponents();
        setName(NbBundle.getMessage(DictionariesTopComponent.class, "CTL_DictionariesTopComponent"));
        setToolTipText(NbBundle.getMessage(DictionariesTopComponent.class, "HINT_DictionariesTopComponent"));
//        setIcon(Utilities.loadImage(ICON_PATH, true));
        
        initCustom();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        setLayout(new java.awt.BorderLayout());
    }// </editor-fold>//GEN-END:initComponents
    // Variables declaration - do not modify//GEN-BEGIN:variables
    // End of variables declaration//GEN-END:variables
    /**
     * Gets default instance. Do not use directly: reserved for *.settings files only,
     * i.e. deserialization routines; otherwise you could get a non-deserialized instance.
     * To obtain the singleton instance, use {@link #findInstance}.
     */
    public static synchronized DictionariesTopComponent getDefault() {
        if (instance == null) {
            instance = new DictionariesTopComponent();
        }
        return instance;
    }

    /**
     * Obtain the DictionariesTopComponent instance. Never call {@link #getDefault} directly!
     */
    public static synchronized DictionariesTopComponent findInstance() {
        TopComponent win = WindowManager.getDefault().findTopComponent(PREFERRED_ID);
        if (win == null) {
            Logger.getLogger(DictionariesTopComponent.class.getName()).warning(
                    "Cannot find " + PREFERRED_ID + " component. It will not be located properly in the window system.");
            return getDefault();
        }
        if (win instanceof DictionariesTopComponent) {
            return (DictionariesTopComponent) win;
        }
        Logger.getLogger(DictionariesTopComponent.class.getName()).warning(
                "There seem to be multiple components with the '" + PREFERRED_ID +
                "' ID. That is a potential source of errors and unexpected behavior.");
        return getDefault();
    }

    @Override
    public int getPersistenceType() {
        return TopComponent.PERSISTENCE_ALWAYS;
    }

    /** replaces this in object stream */
    @Override
    public Object writeReplace() {
        return new ResolvableHelper();
    }

    @Override
    protected String preferredID() {
        return PREFERRED_ID;
    }

    final static class ResolvableHelper implements Serializable {

        private static final long serialVersionUID = 1L;

        public Object readResolve() {
            return DictionariesTopComponent.getDefault();
        }
    }
    
    private void initCustom() {
        tabbedPane = TabbedPaneFactory.createCloseButtonTabbedPane();
        tabbedPane.addPropertyChangeListener( TabbedPaneFactory.PROP_CLOSE, new PropertyChangeListener() {
            public void propertyChange(PropertyChangeEvent evt) {
                JTabbedPane pane = (JTabbedPane)evt.getSource();
                //int sel = pane.getSelectedIndex();
                DictionaryPane dictPane = (DictionaryPane)pane.getSelectedComponent();
                if (dictPane == null) { return; }
                dictPane.removeHyperlinkListener(hyperlinkListener);
                //pane.removeTabAt(sel);
                pane.remove(dictPane);
            }
        });
        this.add(BorderLayout.CENTER, tabbedPane);
        
        hyperlinkListener = new HyperlinkListener() {
            public void hyperlinkUpdate(HyperlinkEvent evt) {
                DictionariesTopComponent.this.hyperlinkUpdate(evt);
            }
        };
        
        
        /* //TODO Change this by get value from preferences default Dictionary
        List dicts = Books.installed().getBooks(BookFilters.getDictionaries());
        Book dict = (Book) dicts.get(0);
        tabbedPane.addTab(dict.getInitials() + "   ", null, new DictionaryPane(dict), dict.getName());
         */
    }
    
    public void openURI(SwordURI uri) {
        if (uri.getType() != SwordURI.Type.DICTIONARY) { return; }
            
        Book dict =  Books.installed().getBook(uri.getPath());
        
        int index = -1;
        
        // find if the dictionary already opened or not
        for (int i=0; i<tabbedPane.getTabCount(); i++) {
            DictionaryPane dictPane = (DictionaryPane)tabbedPane.getComponentAt(i);
            if (dictPane.getBook().getInitials().equals(dict.getInitials())) {
                index = i;
                break;
            }
        }
        
        if (index == -1) {
            DictionaryPane dictPane = new DictionaryPane(dict);
            dictPane.addHyperlinkListener(hyperlinkListener);
            
            tabbedPane.addTab(dict.getInitials() + "  ", null, dictPane, dict.getName());
            index = tabbedPane.getTabCount() - 1;
        }
        
        tabbedPane.setSelectedIndex(index);
    }
    
    private void hyperlinkUpdate(HyperlinkEvent evt) {
        EventType eventType = evt.getEventType();
        String uri = evt.getDescription();
        if (eventType.equals(HyperlinkEvent.EventType.ACTIVATED)) {
            String[] parts = null;
            try {
                parts = SwordURI.parseParts(uri);
                if (parts[2].length() > 0) {
                    if (parts[2].charAt(0) == '#') {
                        return;
                    }
                }
            } catch (URISyntaxException ex) {
                Logger logger = Logger.getLogger(DictionariesTopComponent.class.getName());
                logger.log(Level.WARNING, null, ex);
            }

            if (parts != null) {
                SwordURI swordURI = SwordURI.createURI(SwordURI.BIBLE_SCHEME, parts[1], parts[2]);
                if (swordURI != null) {
                    BookViewManager.getInstance().openURI(swordURI);
                }
            }
        } else if (eventType.equals(HyperlinkEvent.EventType.ENTERED)) {
            StatusDisplayer.getDefault().setStatusText(uri);
        }
    }
}
