/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.netbeans.modules.uihandler;

import java.awt.EventQueue;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyVetoException;
import java.util.Arrays;
import java.util.Comparator;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.EditorKit;
import org.openide.explorer.ExplorerManager;
import org.openide.explorer.view.ChoiceView;
import org.openide.nodes.Node;
import org.openide.text.CloneableEditorSupport;
import org.openide.util.Exceptions;
import org.openide.util.RequestProcessor;

/**
 *
 * @author  Jaroslav Tulach
 */
public class SubmitPanel extends javax.swing.JPanel 
        implements ExplorerManager.Provider, PropertyChangeListener, CaretListener, Comparator<Object>, Runnable {

    private EditorKit betterXMLKit;

    @SuppressWarnings("LeakingThisInConstructor")
    public SubmitPanel() {
        manager = new ExplorerManager();

        initComponents();
        RequestProcessor.getDefault().post(this);
    }

    @Override
    public void run() {
        if (EventQueue.isDispatchThread()) {
            try {
                String content = text.getDocument().getText(0, text.getDocument().getLength());
                text.setEditorKit(betterXMLKit);
                setText(content);
            } catch (BadLocationException ex) {
                Exceptions.printStackTrace(ex);
            }
        } else {
            betterXMLKit = CloneableEditorSupport.getEditorKit("text/xml");
            if (betterXMLKit != null) {
                EventQueue.invokeLater(this);
            }
        }
    }
   
    @Override
    public void addNotify() {
        super.addNotify();
        
        text.addCaretListener(this);
        manager.addPropertyChangeListener(this);
    }
    
    /** 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() {

        try {
            remove = new javax.swing.JComboBox();
            jLabel1 = new javax.swing.JLabel();
            jScrollPane2 = new javax.swing.JScrollPane();
            text = new javax.swing.JEditorPane();

            setPreferredSize(new java.awt.Dimension(640, 480));

            remove.setModel(null );
        } catch (Exception ex) {
        }
        remove = new ChoiceView();

        jLabel1.setText(org.openide.util.NbBundle.getMessage(SubmitPanel.class, "SubmitPanel.jLabel1.text_1")); // NOI18N

        text.setEditable(false);
        jScrollPane2.setViewportView(text);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(remove, 0, 507, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(remove, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 203, Short.MAX_VALUE)
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    @Override
    public ExplorerManager getExplorerManager() {
        return manager;
    }

    void setText(String content){
        try {
            text.getDocument().remove(0, text.getDocument().getLength());
            text.getDocument().insertString(0, content, null);
            text.getCaret().setDot(0);
        } catch (BadLocationException ex) {
            Exceptions.printStackTrace(ex);
        }
    }
    
    @Override
    public void propertyChange(PropertyChangeEvent ev) {
        if (ExplorerManager.PROP_SELECTED_NODES.equals(ev.getPropertyName())) {
            Node[] arr = getExplorerManager().getSelectedNodes();
            if (arr.length != 1) {
                return;
            }

            Object o = arr[0].getValue("offset"); // NOI18N
            if (o instanceof Integer) {
                text.removeCaretListener(this);
                text.getCaret().setDot((Integer)o);
                text.addCaretListener(this);
                text.requestFocus();
            }
        }
    }
    
    @Override
    public void caretUpdate(CaretEvent e) {
        int offset = text.getCaretPosition();
        
        Node[] arr = getExplorerManager().getRootContext().getChildren().getNodes(true);
        int index = Arrays.binarySearch(arr, offset, this);
        if (index < -1) {
            index = -index - 2;
        }
        if (index >= 0 && index < arr.length) {
            try {
                getExplorerManager().removePropertyChangeListener(this);
                getExplorerManager().setSelectedNodes(new Node[]{arr[index]});
            } catch (PropertyVetoException ex) {
                Exceptions.printStackTrace(ex);
            } finally {
                getExplorerManager().addPropertyChangeListener(this);
            }
        }
    }

    @Override
    public int compare(Object o1, Object o2) {
        if (o1 instanceof Node) o1 = ((Node)o1).getValue("offset"); // NOI18N
        if (o2 instanceof Node) o2 = ((Node)o2).getValue("offset"); // NOI18N
        
        if (o1 instanceof Integer && o2 instanceof Integer) {
            return ((Integer)o1) - ((Integer)o2);
        }
        throw new IllegalArgumentException("o1: " + o1 + " o2: " + o2); // NOI18N
    }
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JComboBox remove;
    private javax.swing.JEditorPane text;
    // End of variables declaration//GEN-END:variables
    
    
    private ExplorerManager manager;
}
