
package shapeUtil;

import java.awt.*;
import java.awt.geom.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.border.Border.*;
import javax.swing.text.*;
import java.io.File.*;
import util.*;
import menu.*;
import DrawTop.*;
import shape.*;

public class ComponentLibDialog extends JDialog{
    ComponentAction action;
    ComponentManager componentManager;
    ComponentLibPanel componentLibPanel;
    JLabel messageLabel1=new JLabel(" ");
    JLabel messageLabel2=new JLabel(" ");
    MButton addButton=null;
    MButton deleteButton=null;
    MButton changeButton=null;
    //MButton guideButton=null;
    JScrollPane scrollPane=null;
    Dimension buttonDimension=new Dimension(140, 22);
    Dimension messageDimension=new Dimension(300, 14);
    Point dialogLocation=new Point(500, 90);
    int debug=0;
    
    public ComponentLibDialog(){
        super(ObjectTable.getDrawMain(), "component lib");
        this.setName(Command.getCommandString(Command.LIB));
        this.action=new ComponentAction(this);
        this.componentManager=new ComponentManager(this);
        this.componentLibPanel=new ComponentLibPanel(this);
        this.createDialog();
    }
    
    public void createDialog(){
      //set Window action  
        this.addWindowListener(this.action);
      //dialog layout
        Container contentPane=this.getContentPane();
        Box box=Box.createVerticalBox();
        box.setBackground(Color.GREEN);
        box.setForeground(Color.MAGENTA);
        contentPane.add(box);

     //ScrollPane
        this.scrollPane=new JScrollPane();
        this.scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
        this.scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        JViewport viewport=new JViewport();
        this.scrollPane.setViewport(viewport);
        this.componentLibPanel.setAutoscrolls(true);
        viewport.setView(this.componentLibPanel);
        viewport.setViewPosition(new Point(0,0));
      //OK, Cancel Button    
        JPanel buttonPanel1=new JPanel();
        JPanel buttonPanel2=new JPanel();
        JPanel buttonPanel3=new JPanel();
        this.addButton=   new MButton("add component");
        this.deleteButton=new MButton("del component");
        this.changeButton=new MButton("change shapes");
        //this.guideButton= new MButton("operation guide");
        
        String tipText="Select a shape on the canvas and press this button,\n"
                + " then the selected shape will be added to the upper panel.";
        this.addButton.setToolTipText(tipText);
        this.addButton.setToolTipFont(Font.BOLD);
        tipText="Select a component on the upper panel and press this button,\n"
                + " then the selected component will be deleted.";
        this.deleteButton.setToolTipText(tipText);
        this.deleteButton.setToolTipFont(Font.BOLD);
        tipText="Select a component on the upper panel,select a shape on the canvas,\n"
                + ", and press this bottn, then the selected shape will be changes.";
        this.changeButton.setToolTipText(tipText);
        this.changeButton.setToolTipFont(Font.BOLD);
        
        this.setButtonAttribute(this.addButton, "add",this.action, this.buttonDimension);
        this.setButtonAttribute(this.deleteButton, "delete",this.action, this.buttonDimension);
        this.setButtonAttribute(this.changeButton, "change",this.action, this.buttonDimension);
        //this.setButtonAttribute(this.guideButton, "guide",this.action, this.buttonDimension);

        buttonPanel1.add(this.addButton);
        buttonPanel1.add(this.deleteButton);
        buttonPanel2.add(this.changeButton);
        //buttonPanel3.add(this.guideButton);
      // description Panel
        JPanel descriptionPanel=new JPanel();
        descriptionPanel.setBorder(BorderFactory.createTitledBorder("operation"));
      //messageLabel
        JPanel messagePanel=new JPanel();
        messagePanel.setBorder(BorderFactory.createTitledBorder("message:"));
        Box messageBox=Box.createVerticalBox();
        messagePanel.add(messageBox);
        messageBox.add(Box.createVerticalStrut(0));
        messageBox.add(this.messageLabel1);
        messageBox.add(Box.createVerticalStrut(0));
        messageBox.add(this.messageLabel2);
        messageBox.add(Box.createVerticalStrut(0));
        //messagePanel.setPreferredSize(new Dimension(300,40));
        this.messageLabel1.setPreferredSize(this.messageDimension);
        this.messageLabel2.setPreferredSize(this.messageDimension);
       
        Box descriptionBox=Box.createVerticalBox();
        descriptionPanel.add(descriptionBox);
        JLabel label1=new JLabel();
        label1.setBorder(BorderFactory.createTitledBorder(" add component"));
        label1.setHorizontalTextPosition(SwingConstants.LEFT);
        String str="Select shapes on the screen, then click add component button";
        label1.setText(str);
        label1.setBackground(Color.YELLOW);
        descriptionPanel.add(label1);

      //deploy all components on the dialog
        box.add(this.scrollPane);
        box.add(Box.createVerticalStrut(0));
        box.add(buttonPanel1);
        box.add(Box.createVerticalStrut(0));
        box.add(buttonPanel2);
        box.add(Box.createVerticalStrut(0));
        //box.add(buttonPanel3);
        box.add(Box.createVerticalStrut(0));
        box.add(messagePanel);
    }

    private void setButtonAttribute(JButton button, String actionCommand,
            ActionListener action, Dimension dimension) {
        button.setFont(MenuConstants.MenuFont);
        button.setActionCommand(actionCommand);
        button.addActionListener(action);
        button.setPreferredSize(dimension);
    }

    public void showDialog(){
       //---------------------------------------//
        this.componentManager.readComponentList();
       //---------------------------------------// 
        this.componentLibPanel.repaint();
        if(debug>0) this.printView(this);
        this.scrollPane.setPreferredSize(this.componentLibPanel.getSizeOfScrollPane());
        //dialog position
        Component owner = this.getOwner();
        Point pos = new Point(owner.getX() + (int)this.dialogLocation.getX(),
                owner.getY() + (int)this.dialogLocation.getY());
        this.setLocation(pos);
        this.pack();
        this.setVisible(true);
        ObjectTable.getMenuUtil().setMenuComponent(this.getDialog());
    }
    
    public void showMessage(String message, Color color){
        //System.out.println(" -- showMessage message="+message);
        this.messageLabel1.setForeground(color);
        this.messageLabel2.setForeground(color);
        this.messageLabel1.setFont(DrawParameters.Font12Bold);
        this.messageLabel2.setFont(DrawParameters.Font12Bold);
        int index=message.indexOf("\n");
        String str1=message;
        String str2="";
        if(index>0){
            str1=message.substring(0, index);
            if(index+1<message.length()){
                str2=message.substring(index+1, message.length());
            }
        }
        this.messageLabel1.setText(str1);
        this.messageLabel2.setText(str2);
    }
//DrawMenuIF method
    public String getName(){
        String name=Command.getCommandString(Command.LIB);
        return name;
    }
//DrawMenuIF method
    public void setSelected(boolean selected){}
    
//DrawMenuIF method
    public boolean isSelected(){
        return false;
    }
    
    public ShapeContainer getSelectedComponent(){
        int index=this.componentLibPanel.getSelectedComponentByIndex();
        if(index<0) return null;
        ContainerManager containerManager=this.componentManager.getContainerManager();
        ShapeContainer selectedContainer=containerManager.getContainer(index);
        return selectedContainer;
    }
/*
    protected ContainerManager getContainerManager(){
        return this.componentManager.getContainerManager();
*/
    protected ComponentLibPanel getComponentLibPanel(){
        return this.componentLibPanel;
    }

    protected ComponentManager getComponentManager(){
        return this.componentManager;
    }
    
    protected JScrollPane getScrollPane(){
        return this.scrollPane;
    }
    
    protected JDialog getDialog(){
        return this;
    }
    
    private void printView(ComponentLibDialog dialog){
        System.out.println("++ printView ComponentLibDialog" +
            "\n   dialog:"+Util.Rect(this)+
            "\n   scrollPane:"+Util.Rect(this.scrollPane)+
            "\n   componentLibPanel:"+Util.Rect(this.componentLibPanel));
    }
}

//class ComponentAction extends AbstractAction implements WindowListener {
class ComponentAction extends AbstractAction implements WindowListener, MouseListener {
    ComponentLibDialog dialog;
    String actionButtonName="";
    int debug=0;

    ComponentAction(ComponentLibDialog dialog){
        this.dialog=dialog;
    }

    public void actionPerformed(ActionEvent e) {
        //int debug=MenuUtil.debug;
        String commandName=e.getActionCommand();
        String componentClassName="";
        componentClassName=e.getSource().getClass().getSimpleName();
        String componentName=((Component)e.getSource()).getName();
        if(debug>0) System.out.println("- ComponentAction.actionPerformed  " +
                "commandName="+commandName+
                ", source component name="+componentName+
                ", source class simple name="+componentClassName);

        this.dialog.showMessage(" ", Color.BLACK);
        if(commandName.equals("add")){
            //System.out.println(" -- actionPerformed Add");
            this.actionButtonName="add";
            boolean added=this.addComponent();
            if(added){
                this.dialog.showMessage("Succeeded.", Color.BLUE);
            }
            return;
        }
        if(commandName.equals("delete")){
            //System.out.println(" -- actionPerformed delete");
            this.actionButtonName="delete";
            boolean deleted=this.deleteComponent();
            if(deleted){
                this.dialog.showMessage("Succeeded.", Color.BLUE);
            }
            return;
        }
        if(commandName.equals("change")){
            //System.out.println(" -- actionPerformed change");
            this.actionButtonName="change";
            ChangeShapeElement changeElement=new ChangeShapeElement(this.dialog);
            changeElement.start();
            boolean changed=true;
            if(changed){
                this.dialog.showMessage("Succeeded.", Color.BLUE);
            }
            return;
        }

    }//End of actionPerformed

    public String getActionButtonName(){
        return this.actionButtonName;
    }

    public void mouseClicked(MouseEvent e) {
        if(debug>0) System.out.println("ComponentAction mouseClicked");
        //int index=this.dialog.componentLibPanel.getSelectedComponentByIndex();
    }

    private boolean addComponent(){
        ContainerManager manager=ObjectTable.getContainerManager("");
        ShapeContainer[] containers=manager.getSelectedContainers();
        int size=0;
        if(containers!=null) size=containers.length;
        //boolean added=true;
        if(size==0){
            this.dialog.showMessage("Selected a shape on the canvas !", Color.RED);
            return false;
        }
        for(int i=0;i<size;i++){
            Rectangle2D currentBox=containers[i].getBoundingBox();
            ComponentLibPanel componentLibPanel=this.dialog.getComponentLibPanel();
            Dimension componentSize=componentLibPanel.sizeOfComponent;
            double scaleX=componentSize.getWidth()/currentBox.getWidth();
            double scaleY=componentSize.getHeight()/currentBox.getHeight();
            double scale=Math.min(scaleX, scaleY);
            Rectangle2D newBox=new Rectangle2D.Double(0,0,scale*currentBox.getWidth(),
                    scale*currentBox.getHeight());
            ShapeContainer container=(ShapeContainer)containers[i].clone();
            container.getElement().moveResize(currentBox, newBox, true);
            ContainerManager containerManager=this.dialog.getComponentManager().getContainerManager();
           //-------------------------------//
            container.setNewShapeId( containerManager, true);
             containerManager.addContainer(container);
            if(debug>0)  containerManager.printContainers("++ addComponentToLib");
            ComponentManager componentManager=this.dialog.getComponentManager();
          //-----------------------------------//
            componentManager.writeComponentList();
          //-----------------------------------//
            //componentLibPanel.setComponents(dialogManager.getContainers());
            componentLibPanel.revalidate();
            componentLibPanel.repaint();
        }
        return true;
    }

    private boolean deleteComponent(){
        ContainerManager containerManager=this.dialog.getComponentManager().getContainerManager();
        ComponentLibPanel componentLibPanel=this.dialog.getComponentLibPanel();
        int selectedComponentIndex=componentLibPanel.getSelectedComponentByIndex();
        //System.out.println("++ delComponentFromLib selectedComponentIndex="+selectedComponentIndex);
        int size=containerManager.size();
        if(selectedComponentIndex<0){
            this.dialog.showMessage("No component is selected "
                    + "on the dialog!", Color.RED);
            return false;
        }
        if(selectedComponentIndex>=0&&selectedComponentIndex<size) {
            int returnCode=JOptionPane.showConfirmDialog(ObjectTable.getDrawMain(),
                "Delete selected component?" +
                " Are you sure ?", "", JOptionPane.YES_NO_OPTION);
            if(returnCode==JOptionPane.NO_OPTION) return false;
            containerManager.deleteContainer(selectedComponentIndex);
            this.dialog.getComponentLibPanel().setSelectedComponentByIndex(-1);
        }
        ComponentManager componentManager=this.dialog.getComponentManager();
      //-----------------------------------//
        componentManager.writeComponentList();
      //-----------------------------------//
        //componentLibPanel.setComponents(dialogManager.getContainers());
        componentLibPanel.revalidate();
        componentLibPanel.repaint();
        return true;
    }

    private void closeDialog(){
        ComponentLibDialog dialog=this.dialog;
        Component owner = dialog.getOwner();
        Point dialogPT = dialog.getLocation();
        dialog.dialogLocation = new Point((int) dialogPT.getX() - owner.getX(),
                (int) dialogPT.getY() - owner.getY()); 
        this.dialog.getDialog().setVisible(false);
        ObjectTable.getMenuUtil().removeMenuComponent(this.dialog.getDialog());
        //ObjectTable.getExecCommand()
        return;
    }

    public void windowActivated(WindowEvent e) {}
    public void windowClosed(WindowEvent e) {}
    public void windowClosing(WindowEvent e) {
        this.closeDialog();
    }
    public void windowDeactivated(WindowEvent e) {}
    public void windowDeiconified(WindowEvent e) {}
    public void windowIconified(WindowEvent e) {}
    public void windowOpened(WindowEvent e) {}

    public void mousePressed(MouseEvent e) {
        //System.out.println("Lib panel pressed");
    }
    public void mouseReleased(MouseEvent e) {}
    public void mouseEntered(MouseEvent e) {}
    public void mouseExited(MouseEvent e) {}
} // end of class

