#
# Copyright (c) 2002, 2003, 2004 Art Haas
#
# This file is part of PythonCAD.
#
# PythonCAD is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# PythonCAD is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with PythonCAD; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
#
# vertical construction lines
#

from __future__ import generators

import conobject
import entity
import tolerance
import point
import quadtree
import logger

class VCLine(conobject.ConstructionObject):
    """A base class for horizontal construction lines.
    """
    messages = {
        'moved' : True,
        'keypoint_changed' : True
    }
    def __init__(self, p, **kw):
        """Instantiate an VCLine object.

VCLine(p)

        """
        _p = p
        if not isinstance(p, point.Point):
            _p = point.Point(p)
        conobject.ConstructionObject.__init__(self, **kw)
        self.__keypoint = _p
        _p.storeUser(self)
        _p.connect('moved', self, VCLine.movePoint)

    def __eq__(self, obj):
        """Compare one VCLine to another for equality.
        """
        if not isinstance(obj, VCLine):
            return False
        if obj is self:
            return True
        if abs(self.getLocation().x - obj.getLocation().x) < 1e-10:
            return True
        return False

    def __ne__(self, obj):
        """Compare one VCLine to another for inequality.
        """
        if not isinstance(obj, VCLine):
            return True
        if obj is self:
            return False
        if abs(self.getLocation().x - obj.getLocation().x) < 1e-10:
            return False
        return True

    def __str__(self):
        _x, _y = self.getLocation().getCoords()
        return "Vertical Construction Line at x = %g" % self.__keypoint.x

    def getValues(self):
        return 'vcline', entity.Entity.getValues(self), self.__keypoint.getID()

    def getLocation(self):
        return self.__keypoint

    def setLocation(self, p):
        if self.isLocked():
            raise RuntimeError, "Setting keypoint not allowed - object locked."
        if not isinstance(p, point.Point):
            raise TypeError, "Invalid keypoint: " + `p`
        _kp = self.__keypoint
        if p is not _kp:
            _x = _kp.x
            _kp.disconnect(self)
            _kp.freeUser(self)
            self.__keypoint = p
            self.sendMessage('keypoint_changed', _kp)
            p.connect('moved', self, VCLine.movePoint)
            p.storeUser(self)
            if abs(_x - p.x) > 1e-10:
                self.sendMessage('moved', _x, p.y)
            self.sendMessage('modified')

    def mapCoords(self, x, y, tol=tolerance.TOL):
        """Return the nearest Point on the VCLine to a coordinate pair.

mapCoords(x, y[, tol])

The function has two required argument:

x: A Float value giving the "x" coordinate
y: A Float value giving the "y" coordinate

There is a single optional argument:

tol: A float value equal or greater than 0.0

This function is used to map a possibly near-by coordinate pair to
an actual Point on the VCLine. If the distance between the actual
Point and the coordinates used as an argument is less than the tolerance,
the actual Point is returned. Otherwise, this function returns None.
        """
        _x = x
        if not isinstance(_x, float):
            _x = float(x)
        _y = y
        if not isinstance(_y, float):
            _y = float(y)
        _t = tolerance.toltest(tol)
        _vx = self.__keypoint.x
        if abs(_vx - x) < _t:
            return _vx, _y
        return None

    def inRegion(self, xmin, ymin, xmax, ymax, fully=False):
        """Return whether or not an VCLine passes through a region.

inRegion(xmin, ymin, xmax, ymax)

The first four arguments define the boundary. The method
will return True if the VCLine falls between xmin and xmax.
Otherwise the function will return False.
        """
        _xmin = xmin
        if not isinstance(_xmin, float):
            _xmin = float(xmin)
        _ymin = ymin
        if not isinstance(_ymin, float):
            _ymin = float(ymin)
        _xmax = xmax
        if not isinstance(_xmax, float):
            _xmax = float(xmax)
        if _xmax < _xmin:
            raise ValueError, "Illegal values: xmax < xmin"
        _ymax = ymax
        if not isinstance(_ymax, float):
            _ymax = float(ymax)
        if _ymax < _ymin:
            raise ValueError, "Illegal values: ymax < ymin"
        if fully is not True and fully is not False:
            raise ValueError, "Invalid flag: " + str(fully)
        if fully:
            return False
        _x = self.__keypoint.x
        return _xmin < _x < _xmax

    def move(self, dx, dy):
        """Move a VCLine

move(dx, dy)

The first argument gives the x-coordinate displacement,
and the second gives the y-coordinate displacement. Both
values should be floats.
        """
        if self.isLocked() or self.__keypoint.isLocked():
            raise RuntimeError, "Moving VCLine not allowed - object locked."
        _dx = dx
        if not isinstance(_dx, float):
            _dx = float(dx)
        _dy = dy
        if not isinstance(_dy, float):
            _dy = float(dy)
        if abs(_dx) > 1e-10 or abs(_dy) > 1e-10:
            _x, _y = self.__keypoint.getCoords()
            self.ignore('moved')
            self.__keypoint.move(_dx, _dy)
            self.receive('moved')
            self.sendMessage('moved', _x, _y)
            self.modified()

    def movePoint(self, p, *args):
        _plen = len(args)
        if _plen < 2:
            raise ValueError, "Invalid argument count: %d" % _plen
        _x = args[0]
        if not isinstance(_x, float):
            _x = float(args[0])
        _y = args[1]
        if not isinstance(_y, float):
            _y = float(args[1])
        if p is not self.__keypoint:
            raise ValueError, "Invalid point for VCLine::movePoint()" + `p`
        if abs(p.x - _x) > 1e-10:
            self.sendMessage('moved', _x, _y)
            self.modified()

    def clipToRegion(self, xmin, ymin, xmax, ymax):
        _xmin = xmin
        if not isinstance(_xmin, float):
            _xmin = float(xmin)
        _ymin = ymin
        if not isinstance(_ymin, float):
            _ymin = float(ymin)
        _xmax = xmax
        if not isinstance(_xmax, float):
            _xmax = float(xmax)
        if _xmax < _xmin:
            raise ValueError, "Illegal values: xmax < xmin"
        _ymax = ymax
        if not isinstance(_ymax, float):
            _ymax = float(ymax)
        if _ymax < _ymin:
            raise ValueError, "Illegal values: ymax < ymin"
        _x = self.__keypoint.x
        if _xmin < _x < _xmax:
            return _x, _ymin, _x, _ymax
        return None

    def sendsMessage(self, m):
        if m in VCLine.messages:
            return True
        return conobject.ConstructionObject.sendsMessage(self, m)

def intersect_region(vcl, xmin, ymin, xmax, ymax):
    if not isinstance(vcl, VCLine):
        raise TypeError, "Invalid VCLine: " + str(vcl)
    _xmin = xmin
    if not isinstance(_xmin, float):
        _xmin = float(xmin)
    _ymin = ymin
    if not isinstance(_ymin, float):
        _ymin = float(ymin)
    _xmax = xmax
    if not isinstance(_xmax, float):
        _xmax = float(xmax)
    if _xmax < _xmin:
        raise ValueError, "Illegal values: xmax < xmin"
    _ymax = ymax
    if not isinstance(_ymax, float):
        _ymax = float(ymax)
    if _ymax < _ymin:
        raise ValueError, "Illegal values: ymax < ymin"
    _x, _y = vcl.getLocation().getCoords()
    _x1 = _y1 = _x2 = _y2 = None
    if _xmin < _x < _xmax:
        _x1 = _x
        _y1 = _ymin
        _x2 = _x
        _y2 = _ymax
    return _x1, _y1, _x2, _y2

#
# Quadtree VCLine storage
#

class VCLineQuadtree(quadtree.Quadtree):
    def __init__(self):
        quadtree.Quadtree.__init__(self)

    def getNodes(self, *args):
        _alen = len(args)
        if _alen != 1:
            raise ValueError, "Expected 1 arguments, got %d" % _alen
        _x = args[0]
        if not isinstance(_x, float):
            _x = float(args[0])
        _nodes = [self.getTreeRoot()]
        while len(_nodes):
            _node = _nodes.pop()
            _bounds = _node.getBoundary()
            _xmin = _bounds[0]
            _xmax = _bounds[2]
            if _x < _xmin or _x > _xmax:
                continue
            if _node.hasSubnodes():
                _xmid = (_xmin + _xmax)/2.0
                _ne = _nw = _sw = _se = True
                if _x < _xmid: # vcline to left
                    _ne = _se = False
                else: # vcline to right
                    _nw = _sw = False
                if _ne:
                    _nodes.append(_node.getSubnode(quadtree.QTreeNode.NENODE))
                if _nw:
                    _nodes.append(_node.getSubnode(quadtree.QTreeNode.NWNODE))
                if _sw:
                    _nodes.append(_node.getSubnode(quadtree.QTreeNode.SWNODE))
                if _se:
                    _nodes.append(_node.getSubnode(quadtree.QTreeNode.SENODE))
            else:
                yield _node
      
    def addObject(self, obj):
        if not isinstance(obj, VCLine):
            raise TypeError, "Invalid VCLine object: " + `obj`
        if obj in self:
            return
        _x, _y = obj.getLocation().getCoords()
        _bounds = self.getTreeRoot().getBoundary()
        _xmin = _ymin = _xmax = _ymax = None
        _resize = False
        if _bounds is None: # first node in tree
            _resize = True
            _xmin = _x - 1.0
            _ymin = _y - 1.0
            _xmax = _x + 1.0
            _ymax = _y + 1.0
        else:
            _xmin, _ymin, _xmax, _ymax = _bounds
            if _x < _xmin:
                _xmin = _x - 1.0
                _resize = True
            if _x > _xmax:
                _xmax = _x + 1.0
                _resize = True
            if _y < _ymin:
                _ymin = _y - 1.0
                _resize = True
            if _y > _ymax:
                _ymax = _y + 1.0
                _resize = True
        if _resize:
            self.resize(_xmin, _ymin, _xmax, _ymax)
        for _node in self.getNodes(_x):
            _xmin, _ymin, _xmax, _ymax = _node.getBoundary()            
            if obj.inRegion(_xmin, _ymin, _xmax, _ymax):
                _node.addObject(obj)
        quadtree.Quadtree.addObject(self, obj)
        obj.connect('moved', self, VCLineQuadtree.moveVCLine)

    def old_addObject(self, obj):
        if not isinstance(obj, VCLine):
            raise TypeError, "Invalid VCLine object: " + `obj`
        if obj in self:
            return
        _x, _y = obj.getLocation().getCoords()
        _node = self.getTreeRoot()
        _bounds = _node.getBoundary()
        _xmin = _ymin = _xmax = _ymax = None
        _resize = False
        if _bounds is None: # first node in tree
            _resize = True
            _xmin = _x - 1.0
            _ymin = _y - 1.0
            _xmax = _x + 1.0
            _ymax = _y + 1.0
        else:
            _xmin, _ymin, _xmax, _ymax = _bounds
            if _x < _xmin:
                _xmin = _x - 1.0
                _resize = True
            if _x > _xmax:
                _xmax = _x + 1.0
                _resize = True
            if _y < _ymin:
                _ymin = _y - 1.0
                _resize = True
            if _y > _ymax:
                _ymax = _y + 1.0
                _resize = True
        if _resize:
            self.resize(_xmin, _ymin, _xmax, _ymax)
            _node = self.getTreeRoot()
        _nodes = []
        _nodes.append(_node)
        while len(_nodes):
            _node = _nodes.pop()
            _bounds = _node.getBoundary()
            _xmin = _bounds[0]
            _xmax = _bounds[2]
            if _node.hasSubnodes():
                _xmid = (_xmin + _xmax)/2.0
                _ne = _nw = _sw = _se = True
                if _x < _xmid: # vcline to left
                    _ne = _se = False
                else: # vcline to right
                    _nw = _sw = False
                if _ne:
                    _nodes.append(_node.getSubnode(quadtree.QTreeNode.NENODE))
                if _nw:
                    _nodes.append(_node.getSubnode(quadtree.QTreeNode.NWNODE))
                if _sw:
                    _nodes.append(_node.getSubnode(quadtree.QTreeNode.SWNODE))
                if _se:
                    _nodes.append(_node.getSubnode(quadtree.QTreeNode.SENODE))
            else:
                if (not (_x < _xmin) and (_x < _xmax)):
                    _node.addObject(obj)
        quadtree.Quadtree.addObject(self, obj)
        obj.connect('moved', self, VCLineQuadtree.moveVCLine)

    def delObject(self, obj):
        if obj not in self:
            return
        _pdict = {}
        _x, _y = obj.getLocation().getCoords()
        for _node in self.getNodes(_x):
            _node.delObject(obj)
            _parent = _node.getParent()
            if _parent is not None:
                _pid = id(_parent)
                if _pid not in _pdict:
                    _pdict[_pid] = _parent
        quadtree.Quadtree.delObject(self, obj)
        obj.disconnect(self)
        for _parent in _pdict.values():
            self.purgeSubnodes(_parent)

    def old_delObject(self, obj):
        if obj not in self:
            return
        _x, _y = obj.getLocation().getCoords()
        _nodes = []
        _nodes.append(self.getTreeRoot())
        _pdict = {}
        while len(_nodes):
            _node = _nodes.pop()
            _bounds = _node.getBoundary()
            _xmin = _bounds[0]
            _xmax = _bounds[2]
            if _node.hasSubnodes():
                _xmid = (_xmin + _xmax)/2.0
                _ne = _nw = _sw = _se = True
                if _x < _xmid: # vcline to left
                    _ne = _se = False
                else: # vcline to right
                    _nw = _sw = False
                if _ne:
                    _nodes.append(_node.getSubnode(quadtree.QTreeNode.NENODE))
                if _nw:
                    _nodes.append(_node.getSubnode(quadtree.QTreeNode.NWNODE))
                if _sw:
                    _nodes.append(_node.getSubnode(quadtree.QTreeNode.SWNODE))
                if _se:
                    _nodes.append(_node.getSubnode(quadtree.QTreeNode.SENODE))
            else:
                if (not (_x < _xmin) and (_x < _xmax)):
                    _node.delObject(obj)
                    _parent = _node.getParent()
                    if _parent is not None:
                        _pid = id(_parent)
                        if _pid not in _pdict:
                            _pdict[_pid] = _parent
        quadtree.Quadtree.delObject(self, obj)
        obj.disconnect(self)
        for _parent in _pdict.values():
            self.purgeSubnodes(_parent)

    def find(self, *args):
        _alen = len(args)
        if _alen < 1:
            raise ValueError, "Invalid argument count: %d" % _alen
        _x = args[0]
        if not isinstance(_x, float):
            _x = float(args[0])
        _t = tolerance.TOL
        if _alen > 1:
            _t = tolerance.toltest(args[1])
        if not len(self):
            return None
        _nodes = []
        _nodes.append(self.getTreeRoot())
        _vcl = _tsep = None
        _vdict = {}
        while len(_nodes):
            _node = _nodes.pop()
            _bounds = _node.getBoundary()
            _xmin = _bounds[0]
            _xmax = _bounds[2]
            if (_xmin - _t) < _x < (_xmax + _t):
                if _node.hasSubnodes():
                    for _subnode in _node.getSubnodes():
                        _bounds = _node.getBoundary()
                        _xmin = _bounds[0]
                        _xmax = _bounds[2]
                        if (_xmin - _t) < _x < (_xmax + _t):
                            _nodes.append(_subnode)
                else:
                    for _v in _node.getObjects():
                        _vid = id(_v)
                        if _vid not in _vdict:
                            _xv = _v.getLocation().x
                            _xsep = abs(_xv - _x)
                            if _xsep < _t:
                                if _vcl is None:
                                    _vcl = _v
                                    _tsep = _xsep
                                else:
                                    if _xsep < _tsep:
                                        _vcl = _v
                                        _tsep = _xsep
                            _vdict[_vid] = True
        return _vcl

    def moveVCLine(self, obj, *args):
        if obj not in self:
            raise ValueError, "VCLine not stored in Quadtree: " + `obj`
        _alen = len(args)
        if _alen < 2:
            raise ValueError, "Invalid argument count: %d" % _alen
        _x = args[0]
        if not isinstance(_x, float):
            _x = float(args[0])
        _y = args[1]
        if not isinstance(_y, float):
            _y = float(args[1])
        for _node in self.getNodes(_x):
            _node.delObject(obj) # vcline may not be in node
        quadtree.Quadtree.delObject(self, obj)
        obj.disconnect(self)
        self.addObject(obj)

    def old_moveVCLine(self, obj, *args):
        if obj not in self:
            raise ValueError, "VCLine not stored in Quadtree: " + `obj`
        _alen = len(args)
        if _alen < 2:
            raise ValueError, "Invalid argument count: %d" % _alen
        _x = args[0]
        if not isinstance(_x, float):
            _x = float(args[0])
        _y = args[1]
        if not isinstance(_y, float):
            _y = float(args[1])
        _nodes = []
        _nodes.append(self.getTreeRoot())
        while len(_nodes):
            _node = _nodes.pop()
            _bounds = _node.getBoundary()
            _xmin = _bounds[0]
            _xmax = _bounds[2]
            if _node.hasSubnodes():
                _xmid = (_xmin + _xmax)/2.0
                _ne = _nw = _sw = _se = True
                if _x < _xmid: # vcline to left
                    _ne = _se = False
                else: # vcline to right
                    _nw = _sw = False
                if _ne:
                    _nodes.append(_node.getSubnode(quadtree.QTreeNode.NENODE))
                if _nw:
                    _nodes.append(_node.getSubnode(quadtree.QTreeNode.NWNODE))
                if _sw:
                    _nodes.append(_node.getSubnode(quadtree.QTreeNode.SWNODE))
                if _se:
                    _nodes.append(_node.getSubnode(quadtree.QTreeNode.SENODE))
            else:
                _node.delObject(obj) # vcline may not be in node
        quadtree.Quadtree.delObject(self, obj)
        obj.disconnect(self)
        self.addObject(obj)

    def getClosest(self, x, y, tol=tolerance.TOL):
        return self.find(x, tol)

    def getInRegion(self, xmin, ymin, xmax, ymax):
        _xmin = xmin
        if not isinstance(_xmin, float):
            _xmin = float(xmin)
        _ymin = ymin
        if not isinstance(_ymin, float):
            _ymin = float(ymin)
        _xmax = xmax
        if not isinstance(_xmax, float):
            _xmax = float(xmax)
        if _xmax < _xmin:
            raise ValueError, "Illegal values: xmax < xmin"
        _ymax = ymax
        if not isinstance(_ymax, float):
            _ymax = float(ymax)
        if _ymax < _ymin:
            raise ValueError, "Illegal values: ymax < ymin"
        _vcls = []
        if not len(self):
            return _vcls
        _nodes = []
        _nodes.append(self.getTreeRoot())
        _vdict = {}
        while len(_nodes):
            _node = _nodes.pop()
            if _node.hasSubnodes():
                for _subnode in _node.getSubnodes():
                    _bounds = _subnode.getBoundary()
                    _bmin = _bounds[0]
                    _bmax = _bounds[2]
                    if ((_bmin > _xmax) or (_bmax < _xmin)):
                        continue
                    _nodes.append(_subnode)
            else:
                for _vcl in _node.getObjects():
                    _vid = id(_vcl)
                    if _vid not in _vdict:
                        if _vcl.inRegion(_xmin, _ymin, _xmax, _ymax):
                            _vcls.append(_vcl)
                        _vdict[_vid] = True
        return _vcls

#
# VCLine history class
#

class VCLineLog(logger.Logger):
    def __init__(self, v):
        if not isinstance(v, VCLine):
            raise TypeError, "Invalid VCLine: " + `v`
        logger.Logger.__init__(self)
        self.__v = v
        v.connect('keypoint_changed' ,self, VCLineLog.keypointChange)

    def detatch(self):
        self.__v.disconnect(self)
        self.__v = None

    def keypointChange(self, v, *args):
        _alen = len(args)
        if _alen < 1:
            raise ValueError, "Invalid argument count: %d" % _alen
        _old = args[0]
        if not isinstance(_old, point.Point):
            raise TypeError, "Invalid old endpoint: " + `_old`
        _oid = _old.getID()
        self.saveUndoData('keypoint_changed', _oid)

    def execute(self, undo, *args):
        if undo is not True and undo is not False:
            raise ValueError, "Invalid undo value: " + str(undo)
        _alen = len(args)
        if _alen == 0:
            raise ValueError, "No arguments to execute()"
        _v = self.__v
        _p = _v.getLocation()
        _op = args[0]
        if _op == 'keypoint_changed':
            if _alen < 2:
                raise ValueError, "Invalid argument count: %d" % _alen
            _oid = args[1]
            _cid = _p.getID()
            if undo:
                self.saveRedoData('keypoint_changed', _cid)
                self.ignore('keypoint_changed')
                try:
                    _parent = _v.getParent()
                    if _parent is None:
                        raise ValueError, "VCLine has no parent - cannot undo"
                    _op = _parent.getObject(_oid)
                    if _op is None or not isinstance(_op, point.Point):
                        raise ValueError, "Keypoint missing: id=%d" % _oid
                    _x1, _y1 = _p.getCoords()
                    _v.startUndo(True)
                    try:
                        _v.setLocation(_op)
                    finally:
                        _v.endUndo()
                    if abs(_op.x - _x1) > 1e-10:
                        _v.sendMessage('moved', _x1, _y1)
                finally:
                    self.receive('keypoint_changed')
            else:
                self.saveUndoData('keypoint_changed', _cid)
                _parent = _v.getParent()
                if _parent is None:
                    raise ValueError, "VCLine has no parent - cannot undo"
                _op = _parent.getObject(_oid)
                if _op is None or not isinstance(_op, point.Point):
                    raise ValueError, "Keypoint missing: id=%d" % _oid
                self.ignore('keypoint_changed')
                try:
                    _v.setLocation(_op)
                finally:
                    self.receive('keypoint_changed')
        else:
            raise ValueError, "Unexpected operation: %s" % _op
