package kiyut.alkitab.windows;

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.Serializable;
import java.util.logging.Logger;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import kiyut.alkitab.api.BookViewManager;
import kiyut.alkitab.api.SwordURI;
import kiyut.alkitab.swing.BookshelfTree;
import org.crosswire.jsword.book.Book;
import org.openide.util.NbBundle;
import org.openide.windows.TopComponent;
import org.openide.windows.WindowManager;
//import org.openide.util.Utilities;

/**
 * Top component which displays available book as {@link kiyut.alkitab.swing.BookshelfTree BookshelfTree}.
 */
public final class BookshelfTopComponent extends TopComponent {

    private static BookshelfTopComponent 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 = "BookshelfTopComponent";
    
    private BookshelfTree booksTree;
    
    private BookshelfTopComponent() {
        initComponents();
        setName(NbBundle.getMessage(BookshelfTopComponent.class, "CTL_BookshelfTopComponent"));
        setToolTipText(NbBundle.getMessage(BookshelfTopComponent.class, "HINT_BookshelfTopComponent"));
//        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() {

        scrollPane = new javax.swing.JScrollPane();

        setLayout(new java.awt.BorderLayout());
        add(scrollPane, java.awt.BorderLayout.CENTER);
    }// </editor-fold>//GEN-END:initComponents
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JScrollPane scrollPane;
    // 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 BookshelfTopComponent getDefault() {
        if (instance == null) {
            instance = new BookshelfTopComponent();
        }
        return instance;
    }

    /**
     * Obtain the BookshelfTopComponent instance. Never call {@link #getDefault} directly!
     */
    public static synchronized BookshelfTopComponent findInstance() {
        TopComponent win = WindowManager.getDefault().findTopComponent(PREFERRED_ID);
        if (win == null) {
            Logger.getLogger(BookshelfTopComponent.class.getName()).warning(
                    "Cannot find " + PREFERRED_ID + " component. It will not be located properly in the window system.");
            return getDefault();
        }
        if (win instanceof BookshelfTopComponent) {
            return (BookshelfTopComponent) win;
        }
        Logger.getLogger(BookshelfTopComponent.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 BookshelfTopComponent.getDefault();
        }
    }
    
    @Override
    protected void componentActivated() {
        super.componentActivated();
        booksTree.requestFocusInWindow();
        if (booksTree.getSelectionPath() == null) {
            TreeNode root = (TreeNode) booksTree.getModel().getRoot();
            if (root.getChildCount()>0) {
                booksTree.setSelectionRow(0);
            }
        }
    }
    
    private void initCustom() {
        booksTree = new BookshelfTree();
        scrollPane.setViewportView(booksTree);
        
        booksTree.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent evt) {
                if (evt.getClickCount() != 2) { return; }
        
                TreePath treePath = booksTree.getPathForLocation(evt.getX(), evt.getY());
                if (treePath == null) { return; }
        
                DefaultMutableTreeNode node = (DefaultMutableTreeNode)treePath.getLastPathComponent();
                openSelectedNode(node);
            }
        });
        
        booksTree.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent evt) {
                if (evt.getKeyCode() != KeyEvent.VK_ENTER) {
                    return;
                }
                TreePath treePath = booksTree.getSelectionPath();
                if (treePath == null) { return; }
                DefaultMutableTreeNode node = (DefaultMutableTreeNode)treePath.getLastPathComponent();
                openSelectedNode(node);
            }
        });
    }
    
    
    
    private void openSelectedNode(DefaultMutableTreeNode node) {
        Object obj = node.getUserObject();
        if (!(obj instanceof Book)) {
            return; 
        }
        
        Book book = (Book)obj;
        SwordURI uri = SwordURI.createURI(book,null);
        if (uri != null) {
            BookViewManager.getInstance().openURI(uri,true);
        }
    }
}
