/*
    VLDocking Framework 2.1
    Copyright VLSOLUTIONS, 2004-2006

    email : info@vlsolutions.com
------------------------------------------------------------------------
This software is distributed under the CeCILL license, a GNU GPL-compatible
license adapted to french law.
French and English license headers are provided at the begining of
the source files of this software application.
------------------------------------------------------------------------
LICENCE CeCILL (FRENCH VERSION).
------------------------------------------------------------------------
Ce logiciel est un programme informatique servant à améliorer les interfaces
homme-machine d'applications Java basées sur Swing, en leur apportant un
ensemble de fonctions relatives au dockage des composants.

Ce logiciel est régi par la licence CeCILL soumise au droit français et
respectant les principes de diffusion des logiciels libres. Vous pouvez
utiliser, modifier et/ou redistribuer ce programme sous les conditions
de la licence CeCILL telle que diffusée par le CEA, le CNRS et l'INRIA
sur le site "http://www.cecill.info".

En contrepartie de l'accessibilité au code source et des droits de copie,
de modification et de redistribution accordés par cette licence, il n'est
offert aux utilisateurs qu'une garantie limitée.  Pour les mêmes raisons,
seule une responsabilité restreinte pèse sur l'auteur du programme,  le
titulaire des droits patrimoniaux et les concédants successifs.

A cet égard  l'attention de l'utilisateur est attirée sur les risques
associés au chargement,  à l'utilisation,  à la modification et/ou au
développement et à la reproduction du logiciel par l'utilisateur étant
donné sa spécificité de logiciel libre, qui peut le rendre complexe à
manipuler et qui le réserve donc à des développeurs et des professionnels
avertis possédant  des  connaissances  informatiques approfondies.  Les
utilisateurs sont donc invités à charger  et  tester  l'adéquation  du
logiciel à leurs besoins dans des conditions permettant d'assurer la
sécurité de leurs systèmes et ou de leurs données et, plus généralement,
à l'utiliser et l'exploiter dans les mêmes conditions de sécurité.

Le fait que vous puissiez accéder à cet en-tête signifie que vous avez
pris connaissance de la licence CeCILL, et que vous en avez accepté les
termes.

------------------------------------------------------------------------
CeCILL License (ENGLISH VERSION)
------------------------------------------------------------------------

This software is a computer program whose purpose is to enhance Human-Computer
Interfaces written in Java with the Swing framework, providing them a set of
functions related to component docking.

This software is governed by the CeCILL  license under French law and
abiding by the rules of distribution of free software.  You can  use,
modify and/ or redistribute the software under the terms of the CeCILL
license as circulated by CEA, CNRS and INRIA at the following URL
"http://www.cecill.info".

As a counterpart to the access to the source code and  rights to copy,
modify and redistribute granted by the license, users are provided only
with a limited warranty  and the software's author,  the holder of the
economic rights,  and the successive licensors  have only  limited
liability.

In this respect, the user's attention is drawn to the risks associated
with loading,  using,  modifying and/or developing or reproducing the
software by the user in light of its specific status of free software,
that may mean  that it is complicated to manipulate,  and  that  also
therefore means  that it is reserved for developers  and  experienced
professionals having in-depth computer knowledge. Users are therefore
encouraged to load and test the software's suitability as regards their
requirements in conditions enabling the security of their systems and/or
data to be ensured and,  more generally, to use and operate it in the
same conditions as regards security.

The fact that you are presently reading this means that you have had
knowledge of the CeCILL license and that you accept its terms.

*/



package com.vlsolutions.swing.toolbars;

import com.vlsolutions.swing.docking.AutoHideButton;
import com.vlsolutions.swing.docking.AutoHideButtonPanel;
import com.vlsolutions.swing.docking.Dockable;
import com.vlsolutions.swing.docking.DockableState;
import com.vlsolutions.swing.docking.RelativeDockablePosition;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Container;
import java.util.Collection;
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.util.HashSet;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import org.xml.sax.SAXNotRecognizedException;

/** A utility class used to save and restore toolbars to/from an XML configuration.
 *
 * @author Lilian Chamontin, VLSolutions 
 */
public class ToolBarIO {
  
  /** The main container */
  private ToolBarContainer container;
  
  /** Constructs a new ToolBarIO utility based on the given container */
  public ToolBarIO(ToolBarContainer container) {
    this.container = container;
  }
  
  /** Saves the current toolbar configuration into an XML stream.
   * <p>
   * The stream is not closed at the end of the operation.
   *
   * @see #readXML(InputStream)
   * */
  public void writeXML(OutputStream stream) throws IOException {
    PrintWriter out = new PrintWriter(stream);
    out.println("<?xml version=\"1.0\"?>");
    out.println("<VLToolBars version=\"1.0\">");
    xmlWriteContainer(out);


    out.println("</VLToolBars>");
    out.flush();
  }

  private void xmlWriteContainer(PrintWriter out){
    out.println("<Container>");
    Component [] comps = container.getComponents();
    for (int i=0; i < comps.length; i++){
      Object constraints = container.getConstraints(comps[i]);
      if (constraints.equals(BorderLayout.NORTH)){
        ToolBarPanel panel = container.getToolBarPanelAt(constraints);
        xmlWriteToolBarPanel(out, panel, "top");
      } else if (constraints.equals(BorderLayout.WEST)){
        ToolBarPanel panel = container.getToolBarPanelAt(constraints);
        xmlWriteToolBarPanel(out, panel, "left");
      } else if (constraints.equals(BorderLayout.SOUTH)){
        ToolBarPanel panel = container.getToolBarPanelAt(constraints);
        xmlWriteToolBarPanel(out, panel, "bottom");
      } else if (constraints.equals(BorderLayout.EAST)){
        ToolBarPanel panel = container.getToolBarPanelAt(constraints);
        xmlWriteToolBarPanel(out, panel, "right");
      }
    }
    out.println("</Container>");
  }
  
  private void xmlWriteToolBarPanel(PrintWriter out, ToolBarPanel panel, String position){
    out.println("<ToolBarPanel position=\"" + position + "\">");
    ToolBarPanelLayout layout = (ToolBarPanelLayout) panel.getLayout();
    Component [] children = layout.getComponents(); // toolbars only
    for (int i=0; i < children.length; i++){
      VLToolBar tb = (VLToolBar) children[i];
      ToolBarConstraints tc = layout.getConstraints(tb);
      out.println("<ToolBar name=\"" + tb.getName() + "\" major=\"" + tc.majorOrder + "\" minor=\"" + tc.minorOrder + "\" collapsed=\"" + tb.isCollapsed() + "\"/>");
    }
    out.println("</ToolBarPanel>");
  }
  
  /** Reads an XML encoded stream as the toolbar configuration.
   * <p>
   * When the method returns, the container is totally reconfigured with possibly different
   * toolbars at different positions.
   * <p>
   * <b>Note : </b> The <code>VLToolBar</code>s of the stream must be registered with
   * the {@link ToolBarContainer#registerToolBar(VLToolBar) registerToolBar} method,
   * prior readXML. 
   * <p> Also note that the container must already contain its ToolBarPanels before reading 
   * the configuration.
   *
   * <p>
   * Dismisses all visible toolbars.
   * <p>
   * The stream is not closed at the end of the operation.
   * @see #writeXML(OutputStream)
   * @see ToolBarContainer#registerToolBar(VLToolBar)
   * @return a descriptor of the reading operation(useful for example to know the registered toolbars, that weren't
   *         loaded (missing) from the input file).
   *  */
  public ToolBarIOReadInfo readXML(InputStream in) throws ParserConfigurationException, IOException, SAXException {

    ToolBarIOReadInfo tri = new ToolBarIOReadInfo();
    
    // first clear the toolbar panels
    Component [] comps = container.getComponents();
    for (int i=0; i < comps.length; i++){
      Object constraints = container.getConstraints(comps[i]);
      if (constraints.equals(BorderLayout.NORTH)){
        ((Container)comps[i]).removeAll();
      } else if (constraints.equals(BorderLayout.WEST)){
        ((Container)comps[i]).removeAll();
      } else if (constraints.equals(BorderLayout.SOUTH)){
        ((Container)comps[i]).removeAll();
      } else if (constraints.equals(BorderLayout.EAST)){
        ((Container)comps[i]).removeAll();
      }
    }

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(in);
    Element root = doc.getDocumentElement();
    NodeList children = root.getChildNodes();
    for (int i = 0, len = children.getLength(); i < len; i++) {
      Node child = children.item(i);
      xmlReadRootNode(child, tri);
    }

    tri.setRegisteredToolbars(container.getRegisteredToolBars());
    tri.finishLoading();
    
    container.revalidate();
    
    return tri;
  }

  private void xmlReadRootNode(Node node, ToolBarIOReadInfo tri) throws SAXException{
    if (node.getNodeType() == Node.ELEMENT_NODE){
      Element elt = (Element) node;
      String name = elt.getNodeName();
      if (name.equals("Container")){
        NodeList children = node.getChildNodes();
        for (int i = 0, len = children.getLength(); i < len; i++) {
          Node child = children.item(i);
          xmlReadContainerNode(child, tri);
        }
      } else {
        throw new SAXNotRecognizedException(name);
      }
    }    
  }

  private void xmlReadContainerNode(Node node, ToolBarIOReadInfo tri) throws SAXException{
    if (node.getNodeType() == Node.ELEMENT_NODE){
      Element elt = (Element) node;
      String name = elt.getNodeName();
      if (name.equals("ToolBarPanel")){
        String position = elt.getAttribute("position");
        ToolBarPanel tp = null;
        if (position.equals("top")){
          tp = container.getToolBarPanelAt(BorderLayout.NORTH);
        } else if (position.equals("left")){
          tp = container.getToolBarPanelAt(BorderLayout.WEST);
        } else if (position.equals("bottom")){
          tp = container.getToolBarPanelAt(BorderLayout.SOUTH);
        } else if (position.equals("right")){
          tp = container.getToolBarPanelAt(BorderLayout.EAST);
        }
        NodeList children = elt.getElementsByTagName("ToolBar");
        for (int i = 0, len = children.getLength(); i < len; i++) {
          xmlReadToolBarPanelNode(tp, (Element)children.item(i), tri);
	    }
        tp.revalidate();
      } else {
        throw new SAXNotRecognizedException(name);
      }
    }    
  }

  private void xmlReadToolBarPanelNode(ToolBarPanel panel, Element toolbarElt, ToolBarIOReadInfo tri) {
    String toolbarName = toolbarElt.getAttribute("name");
    int major = Integer.parseInt(toolbarElt.getAttribute("major"));
    int minor = Integer.parseInt(toolbarElt.getAttribute("minor"));
    boolean collapsed = Boolean.valueOf(toolbarElt.getAttribute("collapsed")).booleanValue(); //2.0.6b
    ToolBarConstraints tc = new ToolBarConstraints(major, minor);

    VLToolBar tb = container.getToolBarByName(toolbarName);
    
    if (tb != null) {
        tb.setCollapsed(collapsed); // 2.0.6b
        panel.add(tb, tc);
        tri.notifyToolbarInstalled(tb);
    } else {
        // If the ToolBar is not registered ignore it
      tri.notifyUnknownToolbarFound(toolbarName);
    }
  }
  
}
