#
# Copyright (c) 2003, 2004, 2006 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
#
#
# Transfer objects from one layer to another
#

from PythonCAD.Generic import point
from PythonCAD.Generic import segment
from PythonCAD.Generic import circle
from PythonCAD.Generic import arc
from PythonCAD.Generic import hcline
from PythonCAD.Generic import vcline
from PythonCAD.Generic import acline
from PythonCAD.Generic import segjoint
from PythonCAD.Generic import cline
from PythonCAD.Generic import ccircle
from PythonCAD.Generic import leader
from PythonCAD.Generic import polyline
from PythonCAD.Generic import text
from PythonCAD.Generic import dimension
from PythonCAD.Generic import layer

def _can_xfer(obj, objdict):
    if not isinstance(obj, (text.TextBlock, dimension.Dimension)):
        for _user in obj.getUsers():
            if (not isinstance(_user, dimension.Dimension) and
                id(_user) not in objdict):
                return False
    return True

def _test_pt(pt, objdict, xferlist):
    _pid = id(pt)
    if _pid not in objdict:
        # print "Testing point: " + str(pt)
        if _can_xfer(pt, objdict):
            objdict[_pid] = True
            # print "Transferable ..."
        else:
            objdict[_pid] = False
            # print "Staying behind ..."
        xferlist.append(pt)
        
def old_transfer_objects(objlist, dest):
    """Transfer objects from one layer to another.

transfer_objects(objlist, dest)

objlist: A tuple/list of objects to transfer.
dest: The Layer which will now contain the objects.
    """
    if not isinstance(objlist, (tuple, list)):
        raise TypeError, "Invalid object list: " + `type(objlist)`
    if not isinstance(dest, layer.Layer):
        raise TypeError, "Invalid Layer type: " + `type(dest)`
    _tlist = []
    for _obj in objlist:
        _parent = _obj.getParent()
        if _obj.getParent() is not dest and dest.canParent(_obj):
            _tlist.append(_obj)
    _xferlist = []
    _objdict = {}
    while len(_tlist) > 0:
        _obj = _tlist.pop()
        _xferlist.append(_obj)
        _objdict[id(_obj)] = True
        if isinstance(_obj, point.Point):
            for _user in _obj.getUsers():
                if (not isinstance(_user, dimension.Dimension) and
                    id(_user) not in _objdict):
                    _tlist.append(_obj)
    for _obj in _xferlist:
        if not _can_xfer(_obj, _objdict):
            _objdict[id(_obj)] = False
        if not isinstance(_obj, point.Point):
            if isinstance(_obj, segment.Segment):
                _p1, _p2 = _obj.getEndpoints()
                _test_pt(_p1, _objdict, _xferlist)
                _test_pt(_p2, _objdict, _xferlist)
            elif isinstance(_obj, (circle.Circle, ccircle.CCircle)):
                _test_pt(_obj.getCenter(), _objdict, _xferlist)
            elif isinstance(_obj, arc.Arc):
                _test_pt(_obj.getCenter(), _objdict, _xferlist)
                _layer = _obj.getParent()
                if _layer is not None:
                    _lp = _p1 = _p2 = None
                    for _ep in _obj.getEndpoints():
                        _pts = dest.find('point', _ep[0], _ep[1])
                        if len(_pts) < 1:
                            raise RuntimeError, "No Arc endpoint: " + str(_ep)
                        elif len(_pts) == 1:
                            _lp = _pts[0]
                        else:
                            for _pt in _pts:
                                for _user in _pt.getUsers():
                                    if _user is _obj:
                                        _lp = _user
                                        break
                        if _lp is None:
                            raise RuntimeError, "No Arc endpoint: " + str(_ep)
                        _test_pt(_lp, _objdict, _xferlist)
                        if _p1 is None:
                            _p1 = _lp
                        else:
                            _p2 = _lp
            elif isinstance(_obj, leader.Leader):
                _p1, _p2, _p3 = _obj.getPoints()
                _test_pt(_p1, _objdict, _xferlist)
                _test_pt(_p2, _objdict, _xferlist)
                _test_pt(_p3, _objdict, _xferlist)
            elif isinstance(_obj, polyline.Polyline):
                for _pt in _obj.getPoints():
                    _test_pt(_pt, _objdict, _xferlist)
            elif isinstance(_obj, (hcline.HCLine,
                                   vcline.VCLine,
                                   acline.ACLine)):
                _test_pt(_obj.getLocation(), _objdict, _xferlist)
            elif isinstance(_obj, cline.CLine):
                _p1, _p2 = _obj.getKeypoints()
                _test_pt(_p1, _objdict, _xferlist)
                _test_pt(_p2, _objdict, _xferlist)
            elif isinstance(_obj, (segjoint.Chamfer, segjoint.Fillet)):
                _s1, _s2 = _obj.getSegments()
                if id(_s1) not in _objdict or id(_s2) not in _objdict:
                    _objdict[id(_obj)] = False                    
            elif isinstance(_obj, (text.TextBlock, dimension.Dimension)):
                pass
            else:
                raise TypeError, "Unexpected object type: " + `type(_obj)`
    _xferpts = []
    _xferobjs = []
    for _obj in _xferlist:
        if isinstance(_obj, point.Point):
            _xferpts.append(_obj)
        else:
            _xferobjs.append(_obj)
    for _obj in _xferobjs:
        _layer = _obj.getParent()
        if _layer is not None:
            _layer.delObject(_obj, False)
    for _obj in _xferpts:
        _layer = _obj.getParent()
        if _layer is not None and _objdict[id(_obj)]:
            _layer.delObject(_obj, False)
    _npts = {}
    for _obj in _xferpts:
        _oid = id(_obj)
        if _objdict[_oid]:
            # print "Adding existing point to destination layer ..."
            dest.addObject(_obj)
        else:
            # print "Finding/Making new point for " + `_obj`
            _x, _y = _obj.getCoords()
            _pts = dest.find('point', _x, _y)
            if len(_pts) == 0:
                # print "Making new point ..."
                _np = point.Point(_x, _y)
                dest.addObject(_np)
            else:
                # print "Choosing an existing point ..."
                _np = _pts.pop()
                _max = _np.countUsers()
                for _pt in _pts:
                    _count = _pt.countUsers()
                    if _count > _max:
                        _max = _count
                        _np = _pt
            # print "point bound to new point ..."
            _npts[_oid] = _np
    for _obj in _xferobjs:
        if isinstance(_obj, segment.Segment):
            # print "Testing segment ..."
            _p1, _p2 = _obj.getEndpoints()
            # print "p1: " + `_p1`
            # print "p2: " + `_p2`
            _np = _npts.get(id(_p1))
            if _np is not None:
                # print "Redefining P1: " + `_np`
                _obj.setP1(_np)
            _np = _npts.get(id(_p2))
            if _np is not None:
                # print "Redefining P2: " + `_np`
                _obj.setP2(_np)
        elif isinstance(_obj, (circle.Circle, ccircle.CCircle)):
            _cp = _obj.getCenter()
            _np = _npts.get(id(_cp))
            if _np is not None:
                _obj.setCenter(_np)
        elif isinstance(_obj, arc.Arc):
            _cp = _obj.getCenter()
            _np = _npts.get(id(_cp))
            if _np is not None:
                _obj.setCenter(_np)
            # FIXME: handle endpoints ...
        elif isinstance(_obj, leader.Leader):
            _p1, _p2, _p3 = _obj.getPoints()
            _np = _npts.get(id(_p1))
            if _np is not None:
                _obj.setP1(_np)
            _np = _npts.get(id(_p2))
            if _np is not None:
                _obj.setP2(_np)
            _np = _npts.get(id(_p3))
            if _np is not None:
                _obj.setP3(_np)
        elif isinstance(_obj, polyline.Polyline):
            _pts = _obj.getPoints()
            for _i in range(len(_pts)):
                _pt = _pts[_i]
                _np = _npts.get(id(_pt))
                if _np is not None:
                    _obj.setPoint(_i, _np)
        elif isinstance(_obj, (hcline.HCLine,
                               vcline.VCLine,
                               acline.ACLine)):
            _lp = _obj.getLocation()
            _np = _npts.get(id(_lp))
            if _np is not None:
                _obj.setLocation(_np)
        elif isinstance(_obj, cline.CLine):
            _p1, _p2 = _obj.getKeypoints()
            _np = _npts.get(id(_p1))
            if _np is not None:
                _obj.setP1(_np)
            _np = _npts.get(id(_p2))
            if _np is not None:
                _obj.setP2(_np)
        else:
            pass
        dest.addObject(_obj)

def _dest_pt(lyr, pt):
    _x, _y = pt.getCoords()
    _pts = lyr.find('point', _x, _y)
    if len(_pts) == 0:
        _lpt = pt.clone()
        lyr.addObject(_lpt)
    else:
        _lpt = _pts.pop()
        _max = _lpt.countUsers()
        for _pt in _pts:
            _count = _pt.countUsers()
            if _count > _max:
                _max = _count
                _lpt = _pt
    return _lpt

def _adjust_users(obj, cobjs):
    _oid = id(obj)
    for _user in obj.getUsers():
        if isinstance(_user, dimension.Dimension):
            if isinstance(_user, dimension.LinearDimension):
                _p1, _p2 = _user.getDimPoints()
                if obj is _p1:
                    _user.setP1(cobjs[_oid])
                elif obj is _p2:
                    _user.setP2(cobjs[_oid])
                else:
                    raise RuntimeError, "Point not in linear dimension: " + `_user`
            elif isinstance(_user, dimension.RadialDimension):
                _c = _user.getDimCircle()
                if obj is _c:
                    _user.setDimCircle(cobjs[_oid])
                else:
                    raise RuntimeError, "Circle/Arc not in RadialDimension: " + `_user`
            elif isinstance(_user, dimension.AngularDimension):
                _vp, _p1, _p2 = _user.getDimPoints()
                if obj is _vp:
                    _user.setVertexPoint(cobjs[_oid])
                elif obj is _p1:
                    _user.setP1(cobjs[_oid])
                elif obj is _p2:
                    _user.setP2(cobjs[_oid])
                else:
                    raise RuntimeError, "Point not in AngularDimension: " + `_user`
            else:
                raise TypeError, "Unexpected dimension type:" + `type(_user)`
    
def transfer_objects(objlist, dest):
    """Transfer objects from one layer to another.

transfer_objects(objlist, dest)

objlist: A tuple/list of objects to transfer.
dest: The Layer which will now contain the objects.
    """
    if not isinstance(objlist, (tuple, list)):
        raise TypeError, "Invalid object list: " + `type(objlist)`
    if not isinstance(dest, layer.Layer):
        raise TypeError, "Invalid Layer type: " + `type(dest)`
    #
    # find the valid transferrable entities
    #
    _tlist = []
    for _obj in objlist:
        if _obj.getParent() is not dest and dest.canParent(_obj):
            _tlist.append(_obj)
    #
    # add non-Dimension users of Point objects and
    # connected Segments on Chamfers and Fillets
    #
    _xferlist = []
    _objdict = {}
    while len(_tlist) > 0:
        _obj = _tlist.pop()
        _xferlist.append(_obj)
        _objdict[id(_obj)] = True
        if isinstance(_obj, point.Point):
            for _user in _obj.getUsers():
                if (not isinstance(_user, dimension.Dimension) and
                    id(_user) not in _objdict):
                    _tlist.append(_obj)
        elif isinstance(_obj, (segjoint.Chamfer, segjoint.Fillet)):
            _s1, _s2 = _obj.getSegments()
            if id(_s1) not in _objdict:
                _tlist.append(_s1)
            if id(_s2) not in _objdict:
                _tlist.append(_s2)
        else:
            pass
    #
    # clone objects
    #
    _cobjs = {}
    _dobjs = {}
    for _obj in _xferlist:
        _oid = id(_obj)
        if isinstance(_obj, point.Point):
            if _oid not in _cobjs:
                _cobjs[_oid] = _dest_pt(dest, _obj)
            if _oid not in _dobjs:
                _dobjs[_oid] = _obj
        elif isinstance(_obj, segment.Segment):
            _p1, _p2 = _obj.getEndpoints()
            _pid = id(_p1)
            if _pid not in _cobjs:
                _cobjs[_pid] = _dest_pt(dest, _p1)
            if _pid not in _dobjs:
                _dobjs[_pid] = _p1
            _pid = id(_p2)
            if _pid not in _cobjs:
                _cobjs[_pid] = _dest_pt(dest, _p2)
            if _pid not in _dobjs:
                _dobjs[_pid] = _p2
            _cobjs[_oid] = _obj.clone()
        elif isinstance(_obj, (circle.Circle, ccircle.CCircle)):
            _cp = _obj.getCenter()
            _pid = id(_cp)
            if _pid not in _cobjs:
                _cobjs[_pid] = _dest_pt(dest, _cp)
            if _pid not in _dobjs:
                _dobjs[_pid] = _cp
            _cobjs[_oid] = _obj.clone()
            if isinstance(_obj, circle.Circle) and _oid not in _dobjs:
                _dobjs[_oid] = _obj
        elif isinstance(_obj, arc.Arc):
            _cp = _obj.getCenter()
            _pid = id(_cp)
            if _pid not in _cobjs:
                _cobjs[_pid] = _dest_pt(dest, _cp)
            if _pid not in _dobjs:
                _dobjs[_pid] = _cp
            _cobjs[_oid] = _obj.clone()
            if  _oid not in _dobjs:
                _dobjs[_oid] = _obj
            _layer = _obj.getParent()
            for _ep in _obj.getEndpoints():
                _pts = layer.find('point', _ep[0], _ep[1])
                if len(_pts) == 0:
                    raise RuntimeError, "No points at arc endpoint: " + str(_ep)
                _ept = None
                for _pt in _pts:
                    for _user in _pt.getUsers():
                        if _user is _obj:
                            _ept = _pt
                            break
                if _ept is None:
                    raise RuntimeError, "No Arc endpoint at: " + str(_ep)
                _pid = id(_ept)
                if _pid not in _cobjs:
                    _cobjs[_pid] = _dest_pt(dest, _ept)
                if _pid not in _dobjs:
                    _dobjs[_pid] = _ept
        elif isinstance(_obj, leader.Leader):
            _p1, _p2, _p3 = _obj.getEndpoints()
            _pid = id(_p1)
            if _pid not in _cobjs:
                _cobjs[_pid] = _dest_pt(dest, _p1)
            if _pid not in _dobjs:
                _dobjs[_pid] = _p1
            _pid = id(_p2)
            if _pid not in _cobjs:
                _cobjs[_pid] = _dest_pt(dest, _p2)
            if _pid not in _dobjs:
                _dobjs[_pid] = _p2
            _pid = id(_p3)
            if _pid not in _cobjs:
                _cobjs[_pid] = _dest_pt(dest, _p3)
            if _pid not in _dobjs:
                _dobjs[_pid] = _p3
            _cobjs[_oid] = _obj.clone()
        elif isinstance(_obj, polyline.Polyline):
            for _pt in _obj.getPoints():
                _pid = id(_pt)
                if _pid not in _cobjs:
                    _cobjs[_pid] = _dest_pt(dest, _pt)
                if _pid not in _dobjs:
                    _dobjs[_pid] = _pt
            _cobjs[_oid] = _obj.clone()
        elif isinstance(_obj, (hcline.HCLine,
                               vcline.VCLine,
                               acline.ACLine)):
            _pt = _obj.getLocation()
            _pid = id(_pt)
            if _pid not in _cobjs:
                _cobjs[_pid] = _dest_pt(dest, _pt)
            if _pid not in _dobjs:
                _dobjs[_pid] = _pt
            _cobjs[_oid] = _obj.clone()
        elif isinstance(_obj, cline.CLine):
            _p1, _p2 = _obj.getKeypoints()
            _pid = id(_p1)
            if _pid not in _cobjs:
                _cobjs[_pid] = _dest_pt(dest, _p1)
            if _pid not in _dobjs:
                _dobjs[_pid] = _p1
            _pid = id(_p2)
            if _pid not in _cobjs:
                _cobjs[_pid] = _dest_pt(dest, _p2)
            if _pid not in _dobjs:
                _dobjs[_pid] = _p2
            _cobjs[_oid] = _obj.clone()
        elif isinstance(_obj, (segjoint.Chamfer, segjoint.Fillet)):
            pass
        elif isinstance(_obj, (text.TextBlock,
                               dimension.LinearDimension,
                               dimension.RadialDimension,
                               dimension.AngularDimension)):
            _cobjs[id(_obj)] = _obj.clone()
        else:
            print "Skipping object type" + `type(_obj)`
    #
    # add the cloned objects
    #
    for _obj in _xferlist:
        _cobj = _cobjs.get(id(_obj))
        if isinstance(_obj, point.Point):
            continue
        elif isinstance(_obj, segment.Segment):
            _p1, _p2 = _obj.getEndpoints()
            _cobj.setP1(_cobjs[id(_p1)])
            _cobj.setP2(_cobjs[id(_p2)])
        elif isinstance(_obj, (circle.Circle, arc.Arc, ccircle.CCircle)):
            _cp = _obj.getCenter()
            _cobj.setCenter(_cobjs[id(_cp)])
        elif isinstance(_obj, leader.Leader):
            _p1, _p2, _p3 = _obj.getEndpoints()
            _cobj.setP1(_cobjs[id(_p1)])
            _cobj.setP2(_cobjs[id(_p2)])
            _cobj.setP3(_cobjs[id(_p3)])
        elif isinstance(_obj, polyline.Polyline):
            _pts = _obj.getPoints()
            for _i in range(len(_pts)):
                _pt = _pts[_i]
                _cobj.setPoint(_i, _cobjs[id(_pt)])
        elif isinstance(_obj, (hcline.HCLine,
                               vcline.VCLine,
                               acline.ACLine)):
            _pt = _obj.getLocation()
            _cobj.setLocation(_cobjs[id(_pt)])
        elif isinstance(_obj, cline.CLine):
            _p1, _p2 = _obj.getKeypoints()
            _cobj.setP1(_cobjs[id(_p1)])
            _cobj.setP2(_cobjs[id(_p2)])
        elif isinstance(_obj, (segjoint.Chamfer,
                               segjoint.Fillet)):
            _s1, _s2 = _obj.getSegments()
            _cs1 = _cobjs[id(_s1)]
            _cs2 = _cobjs[id(_s2)]
            _s = _obj.getStyle()
            if isinstance(_obj, segjoint.Chamfer):
                _l = _obj.getLength()
                _cobj = segjoint.Chamfer(_cs1, _cs2, _l, _s)
            else:
                _r = _obj.getRadius()
                _cobj = segjoint.Fillet(_cs1, _cs2, _r, _s)
            _cobj.setColor(_obj.getColor())
            _cobj.setLinetype(_obj.getLinetype())
            _cobj.setThickness(_obj.getThickness())
        elif isinstance(_obj, dimension.LinearDimension):
            _p1, _p2 = _obj.getDimPoints()
            _pid = id(_p1)
            if _pid in _cobjs:
                _cobj.setP1(_cobjs[_pid])
            _pid = id(_p2)
            if _pid in _cobjs:
                _cobj.setP2(_cobjs[_pid])
        elif isinstance(_obj, dimension.RadialDimension):
            _dc = _obj.getDimCircle()
            _dcid = id(_dc)
            if _dcid in _cobjs:
                _cobj.setDimCircle(_cobjs[_dcid])
        elif isinstance(_obj, dimension.AngularDimension):
            _vp, _p1, _p2 = _obj.getDimPoints()
            _pid = id(_vp)
            if _pid in _cobjs:
                _cobj.setVertexPoint(_cobjs[_pid])
            _pid = id(_p1)
            if _pid in _cobjs:
                _cobj.setP1(_cobjs[_pid])
            _pid = id(_p2)
            if _pid in _cobjs:
                _cobj.setP2(_cobjs[_pid])
        elif isinstance(_obj, text.TextBlock):
            pass
        else:
            print "Skipping object type " + `type(_obj)`
            continue
        dest.addObject(_cobj)
    #
    # adjust dimensions
    #
    for _obj in _dobjs.values():
        _adjust_users(_obj, _cobjs)
    #
    # delete the old objects
    #
    for _obj in _xferlist:
        _layer = _obj.getParent()
        if _layer is not None:
            _layer.delObject(_obj)
