/*
    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.docking;

import com.vlsolutions.swing.docking.event.DockDropEvent;
import com.vlsolutions.swing.docking.event.DockDragEvent;
import java.awt.geom.Rectangle2D;
import java.awt.*;
import com.vlsolutions.swing.docking.event.*;

/** An utility class used to delegate the border drag/drop scanning for docking (
 * since the same code is used in many DockDropReceivers).
 * <p>
 * This class is only meant for API Extenders.
 * <p>
 * Taking a DockDragEvent or DockDropEvent, check if mouse is near of one border.
 * If so, accepts the drag or drop operation.
 *
 * @author Lilian Chamontin, vlsolutions.
 * @version 1.0
 * @update 2005/10/21 Lilian Chamontin : updated the shape to show real size of drop (and not 20 pixeles width/height)
 * @update 2005/11/14 Lilian Chamontin : added support for drag and drop of a whole tabbed container
 * @update 2005/12/08 Lilian Chamontin : fixed a bug when dropping into itself
 */

public class BorderSplitter {
  Component delegator;
  
  public BorderSplitter(Component delegator) {
    this.delegator = delegator;
  }
  
  
  public void processDockableDrag(DockDragEvent e){
    scanDrop(e, false);
  }
  
  public void processDockableDrop(DockDropEvent e){
    scanDrop(e, true);
  }
  
  /** This method should be overriden if the delegator doesn't belong to the
   * docking containment hierarchy after drop acceptance.
   * <p> Here is a case :
   * <UL>
   *   <LI>if tabpane is a TabbedDockableContainer with 2 tabs,
   *   <LI>if drag starts on tabpane
   *   <LI>if drop occurs on a border of the same tabpane
   * </UL>
   *
   * <p>
   * Then, tabpane will be replaced by a simple DockableContainer on drop acceptance
   * (because only one tab left).
   * <p>
   * And DockingDesktop.splitContainer(Component base, Split position) cannot be
   * called with tabpane as "base" (instead, it should be called with the replacer of
   * tabpane, or use the other split method which takes a dockable as base.
   *
   *
   * */
  public void split(DockDropEvent event, Container draggedContainer, DockingConstants.Split position){
    /* standard splitting */
//    event.getDesktop().splitComponent(delegator, event.getDragSource().getDockable(),
//        position);
    event.getDesktop().splitComponent(delegator, draggedContainer, position); //2005/11/14
    
  }
  
  private void acceptSplit(DockDropEvent event, DockingConstants.Split position){
    Container container = event.getDragSource().getDockableContainer();
    Dockable dockable = event.getDragSource().getDockable();//2005/12/08
    TabbedDockableContainer tabAncestor = DockingUtilities.findTabbedDockableContainer(dockable);
    ( (DockDropEvent) event).acceptDrop();
    if (container instanceof TabbedDockableContainer){
      split(event, container, position);
    } else {
      if (tabAncestor != null && tabAncestor.getTabCount() == 1 && tabAncestor == delegator){
        // we have detected a dropping onto itself :
        // the drop gesture comes from the tabAncestor (as it's given by the drag source)
        // and translates into a border split
        // if only one tab remains, that means  the tabAncestor is no longer useful and
        // so we now need to remove that tab and replace it by a standard singledockable
        // which is done by the standard desktop "split" public method.
        Dockable remainingDockable = tabAncestor.getDockableAt(0);
        event.getDesktop().split(
            remainingDockable, // the only remaining dockable
            dockable,
            position);
      } else {
        // standard dropping, just use the internal API to relayout the desktop.
        event.getDesktop().splitComponent(delegator, dockable, position);
      }
    }
  }
  
  /** Accept the drag gesture and setup the docking action event associated to it */
  private void acceptDragSplit(DockDragEvent event, DockingConstants.Split position, Shape shape){
    
    Container container = event.getDragSource().getDockableContainer();
    Dockable dockable = event.getDragSource().getDockable();//2005/12/08
    TabbedDockableContainer tabAncestor = DockingUtilities.findTabbedDockableContainer(dockable);
    int initialState = dockable.getDockKey().getDockableState();
    int borderSpliterState = DockingUtilities.getDockableStateFromHierarchy(delegator);
    
    if (container instanceof TabbedDockableContainer){
      event.setDockingAction(new DockingActionSplitComponentEvent(event.getDesktop(), 
          dockable, initialState, borderSpliterState, container, position, 0.5f));
    } else {
      if (tabAncestor != null && tabAncestor.getTabCount() == 1 && tabAncestor == delegator){
        // we have detected a dropping onto itself :
        // the drop gesture comes from the tabAncestor (as it's given by the drag source)
        // and translates into a border split
        // if only one tab remains, that means  the tabAncestor is no longer useful and
        // so we now need to remove that tab and replace it by a standard singledockable
        // which is done by the standard desktop "split" public method.
        Dockable remainingDockable = tabAncestor.getDockableAt(0);
        event.setDockingAction(new DockingActionSplitDockableEvent(event.getDesktop(), 
          dockable, initialState, borderSpliterState, remainingDockable, position, 0.5f));        
      } else {
        // standard dropping, just use the internal API to relayout the desktop.
        event.setDockingAction(new DockingActionSplitComponentEvent(event.getDesktop(), 
          dockable, initialState, borderSpliterState, delegator, position, 0.5f));
      }
    }
    event.acceptDrag(shape);
  }
  
  private void scanDrop(DockEvent event, boolean drop){
    Point p = event.getMouseEvent().getPoint();
    Dimension size = delegator.getSize();
    int distTop = p.y;
    int distLeft = p.x;
    int min = Math.min(distTop, distLeft);
    int distRight = size.width - p.x;
    min = Math.min(min, distRight);
    int distBottom = size.height - p.y;
    min = Math.min(min, distBottom);
    
    Dimension draggedSize = null;
    DockableDragSource source = event.getDragSource();
    
    // the drag size is the one of the parent dockable container
    //draggedSize = dragged.getComponent().getParent().getSize();
    draggedSize = source.getDockableContainer().getSize();
    
    int bestHeight = (int)Math.min(draggedSize.height , size.height * 0.5);
    int bestWidth = (int)Math.min(draggedSize.width , size.width * 0.5);
    
    if (min == distTop && min < delegator.getHeight()/4) {
      // dock on top
      if (drop) {
        acceptSplit((DockDropEvent) event, DockingConstants.SPLIT_TOP);
      } else {
        Rectangle2D r2d = new Rectangle2D.Float(0,
            0,
            size.width,
            bestHeight);
        acceptDragSplit((DockDragEvent) event, DockingConstants.SPLIT_TOP, r2d);
      }
    } else if (min == distLeft && min < delegator.getWidth()/4) {
      if (drop) {
        acceptSplit((DockDropEvent) event, DockingConstants.SPLIT_LEFT);
      } else {
        Rectangle2D r2d = new Rectangle2D.Float(0,
            0,
            bestWidth,
            size.height);
        acceptDragSplit((DockDragEvent) event, DockingConstants.SPLIT_LEFT, r2d);
      }
    } else if (min == distBottom && min < delegator.getHeight()/4) {
      if (drop) {
        acceptSplit((DockDropEvent) event, DockingConstants.SPLIT_BOTTOM);
      } else {
        Rectangle2D r2d = new Rectangle2D.Float(0,
            size.height - bestHeight, //20,
            size.width,
            bestHeight);
        acceptDragSplit((DockDragEvent) event, DockingConstants.SPLIT_BOTTOM, r2d);
      }
    } else if (min == distRight && min < delegator.getWidth()/4){ // right
      if (drop) {
        acceptSplit((DockDropEvent) event, DockingConstants.SPLIT_RIGHT);
      } else {
        Rectangle2D r2d = new Rectangle2D.Float(
            size.width - bestWidth,
            0,
            bestWidth, 
            size.height);
        acceptDragSplit((DockDragEvent) event, DockingConstants.SPLIT_RIGHT, r2d);
        
      }
    }
  }
  
  
}
