#
# Copyright (c) 2003 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
#

import Generic.point
import Generic.circle
import Generic.arc
import Generic.conobject
import Generic.hcline
import Generic.vcline
import Generic.acline
import Generic.segjoint
import Generic.cline
import Generic.ccircle
import Generic.leader
import Generic.polyline
import Generic.text
import Generic.dimension
import Generic.layer
import Generic.image

def _remove_objects(objdict, from_layer):
    _objects = objdict.values()
    for _obj in _objects:
        _oid = id(_obj)
        if objdict[_oid] is not False:
            if isinstance(_obj, Generic.point.Point):
                from_layer.delObject(_obj)
                objdict[_oid] = False
            elif isinstance(_obj, (Generic.segment.Segment,
                                   Generic.cline.CLine)):
                if isinstance(_obj, Generic.segment.Segment):
                    _p1, _p2 = _obj.getEndpoints()
                else:
                    _p1, _p2 = _obj.getKeypoints()
                _pid = id(_p1)
                objdict[_pid] = False
                _pid = id(_p2)
                objdict[_pid] = False
                from_layer.delObject(_obj)
            elif isinstance(_obj, (Generic.circle.Circle,
                                   Generic.arc.Arc,
                                   Generic.ccircle.CCircle)):
                _cp = _obj.getCenter()
                _pid = id(_cp)
                objdict[_pid] = False
                if isinstance(_obj, Generic.arc.Arc):
                    for _ep in _obj.getEndpoints():
                        _lp = from_layer.find('point', _ep[0], _ep[1])
                        if _lp is None:
                            raise ValueError, "No Point at arc endpoint: " + str(_ep)
                        _pid = id(_lp)
                        objdict[_pid] = False
                from_layer.delObject(_obj)
            elif isinstance(_obj, (Generic.hcline.HCLine,
                                   Generic.vcline.VCLine,
                                   Generic.acline.ACLine)):
                _lp = _obj.getLocation()
                _pid = id(_lp)
                objdict[_pid] = False
                from_layer.delObject(_obj)
            elif isinstance(_obj, Generic.leader.Leader):
                _p1, _p2, _p3 = _obj.getPoints()
                _pid = id(_p1)
                objdict[_pid] = False
                _pid = id(_p2)
                objdict[_pid] = False
                _pid = id(_p3)
                objdict[_pid] = False
                from_layer.delObject(_obj)
            elif isinstance(_obj, Generic.polyline.Polyline):
                for _pt in _obj.getPoints():
                    _pid = id(_pt)
                    objdict[_pid] = False
                from_layer.delObject(_obj)
            elif isinstance(_obj, (Generic.segjoint.Chamfer,
                                   Generic.segjoint.Fillet)):
                for _seg in _obj.getSegments():
                    _sid = id(_seg)
                    for _pt in _seg.getEndpoints():
                        _pid = id(_pt)
                        objdict[_pid] = False
                    if objdict[_sid] is not False:
                        from_layer.delObject(_seg)
                        objdict[_sid] = False
            else:
                print "Unexpected deletion type %s" % type(_obj)
            objdict[_oid] = False
    for _oid, _obj in objdict.items():
        if _obj is not False:
            print "Skipped object: " + `_obj`
            print "id: " + _oid
            print "object: " + str(_obj)

def _adjust_dimensions(dimobjs, newobjs, to_layer):
    # print "in adjust_dimensions() ..."
    for _oid, _obj in dimobjs.items():
        # print "testing obj: " + `_obj`
        if _oid not in newobjs:
            raise KeyError, "Object not transfered: " + `_obj`
        _newobj = newobjs[_oid]
        _udict = {}
        for _uref in _obj.getUsers():
            _user = _uref()
            if _user is not None:
                _uid = id(_user)
                if _uid not in newobjs:
                    _udict[_uid] = _user
        _reset = True
        for _user in _udict.values():
            if not isinstance(_user, Generic.dimension.Dimension):
                _reset = False
                break
        # print "reset: " + str(_reset)
        if _reset:
            if isinstance(_obj, Generic.point.Point):
                for _dim in _udict.values():
                    if isinstance(_dim, Generic.dimension.LinearDimension):
                        _p1, _p2 = _dim.getDimPoints()
                        if _obj is _p1:
                            _dim.setP1(to_layer, _newobj)
                        elif _obj is _p2:
                            _dim.setP2(to_layer, _newobj)
                        else:
                            raise ValueError, "Point not used in linear dimension: " + `_dim`
                    elif isinstance(_dim, Generic.dimension.AngularDimension):
                        _vp, _p1, _p2 = _dim.getDimPoints()
                        if _obj is _vp:
                            _dim.setVertexPoint(to_layer, _newobj)
                        elif _obj is _p1:
                            _dim.setP1(to_layer, _newobj)
                        elif _obj is _p2:
                            _dim.setP2(to_layer, _newobj)
                        else:
                            raise ValueError, "Point not used in angular dimension: " + `_dim`
                    else:
                        raise TypeError, "Unexpected dim type for point: %s" % type(_dim)
            elif isinstance(_obj, Generic.circle.Circle): # and Arc
                for _dim in _udict.values():
                    if isinstance(_dim, Generic.dimension.RadialDimension):
                        _dim.setDimCircle(to_layer, _newobj)
                    else:
                        raise TypeError, "Unexpected dim type for circle/arc: %s" % type(_dim)
            else:
                raise TypeError, "Unexpected type: %s" % type(_obj)

def _used_in_dimension(obj):
    if isinstance(obj, (Generic.point.Point, Generic.circle.Circle)):
        for _uref in obj.getUsers():
            _user = _uref()
            if _user is not None:
                if isinstance(_user, Generic.dimension.Dimension):
                    return True
    return False

def transfer_objects(objlist, from_layer, to_layer):
    """Transfer objects from one layer to another.

transfer_objects(objlist, from_layer, to_layer)

objlist: A list of objects to transfer.
from_layer: A layer object containing the list of objects
to_layer: A layer object which will recieve the objects in the list
    """
    if not isinstance(objlist, list):
        raise TypeError, "Invalid object list: " + str(objlist)
    if not isinstance(from_layer, Generic.layer.Layer):
        raise TypeError, "Invalid layer: " + str(from_layer)
    if not isinstance(to_layer, Generic.layer.Layer):
        raise TypeError, "Invalid layer: " + str(to_layer)
    for _obj in objlist:
        if _obj not in from_layer:
            raise ValueError, "Object not in layer: " + `_obj`
    #
    # get the various subparts that will have to be transferred
    #
    _objdict = {}
    _dimobjs = {}
    _dtobjs = [] # dimension and text objects are handled specially
    while len(objlist):
        _obj = objlist.pop(0)
        # print "examining obj: " + `_obj`
        _oid = id(_obj)
        if _oid not in _objdict:
            _objdict[_oid] = _obj
        if isinstance(_obj, Generic.point.Point):
            if _used_in_dimension(_obj):
                _dimobjs[_oid] = _obj
        elif isinstance(_obj, (Generic.segment.Segment,
                               Generic.cline.CLine,
                               Generic.leader.Leader,
                               Generic.polyline.Polyline)):
            if isinstance(_obj, Generic.segment.Segment):
                _ptmeth = _obj.getEndpoints
            elif isinstance(_obj, Generic.cline.CLine):
                _ptmeth = _obj.getKeypoints
            elif isinstance(_obj, (Generic.leader.Leader,
                                   Generic.polyline.Polyline)):
                _ptmeth = _obj.getPoints
            for _pt in _ptmeth():
                _pid = id(_pt)
                if _pid not in _objdict:
                    _objdict[_pid] = _pt
                if _used_in_dimension(_pt):
                    _dimobjs[_pid] = _pt
        elif isinstance(_obj, (Generic.circle.Circle,
                               Generic.arc.Arc,
                               Generic.ccircle.CCircle)):
            _cp = _obj.getCenter()
            _cid = id(_cp)
            if _cid not in _objdict:
                _objdict[_cid] = _cp
            if _used_in_dimension(_cp):
                _dimobjs[_cid] = _cp
            if _used_in_dimension(_obj):
                _dimobjs[_oid] = _obj
            if isinstance(_obj, Generic.arc.Arc):
                for _ep in _obj.getEndpoints():
                    _lp = from_layer.find('point', _ep[0], _ep[1])
                    if _lp is None:
                        raise ValueError, "No Point at arc endpoint: " + str(_ep)
                    _lid = id(_lp)
                    if _lid not in _objdict:
                        _objdict[_lid] = _lp
                    if _used_in_dimension(_lp):
                        _dimobjs[_lid] = _lp
        elif isinstance(_obj, (Generic.hcline.HCLine,
                               Generic.vcline.VCLine,
                               Generic.acline.ACLine)):
            _lp = _obj.getLocation()
            _lid = id(_lp)
            if _lid not in _objdict:
                _objdict[_lid] = _lp
            if _used_in_dimension(_lp):
                _dimobjs[_lid] = _lp
        elif isinstance(_obj, (Generic.segjoint.Chamfer,
                               Generic.segjoint.Fillet)):
            objlist.extend(_obj.getSegments())
        elif isinstance(_obj, (Generic.dimension.LinearDimension,
                               Generic.dimension.RadialDimension,
                               Generic.dimension.AngularDimension,
                               Generic.text.TextBlock)):
            del _objdict[_oid]
            _dtobjs.append(_obj)
        else:
            print "Skipping object type %s" % type(_obj)
    #
    # now start moving the things between layers
    #
    _newobjs = {}
    _sjoints = []
    for _oid, _obj in _objdict.items():
        if _oid in _newobjs:
            continue
        if isinstance(_obj, Generic.point.Point):
            _x, _y = _obj.getCoords()
            _pt = to_layer.find('point', _x, _y)
            if _pt is None:
                _pt = _obj.clone()
                to_layer.addObject(_pt)
            _newobjs[_oid] = _pt
        elif isinstance(_obj, (Generic.segment.Segment,
                              Generic.cline.CLine)):
            _seg = False
            if isinstance(_obj, Generic.segment.Segment):
                _p1, _p2 = _obj.getEndpoints()
                _seg = True
            else:
                _p1, _p2 = _obj.getKeypoints()
            _pid = id(_p1)
            if _pid in _newobjs:
                _np1 = _newobjs[_pid]
            else:
                _x, _y = _p1.getCoords()
                _np1 = to_layer.find('point', _x, _y)
                if _np1 is None:
                    _np1 = _p1.clone()
                    to_layer.addObject(_np1)
                _newobjs[_pid] = _np1
            _pid = id(_p2)
            if _pid in _newobjs:
                _np2= _newobjs[_pid]
            else:
                _x, _y = _p2.getCoords()
                _np2 = to_layer.find('point', _x, _y)
                if _np2 is None:
                    _np2 = _p2.clone()
                    to_layer.addObject(_np2)
                _newobjs[_pid] = _np2
            if _seg:
                _newobj = _obj.clone()
                _newobj.setP1(_np1)
                _newobj.setP2(_np2)
                _newobj.reset()
            else:
                _newobj = Generic.cline.CLine(_np1, _np2)
            to_layer.addObject(_newobj)
            _newobjs[_oid] = _newobj
        elif isinstance(_obj, (Generic.leader.Leader,
                               Generic.polyline.Polyline)):
            _leader = False
            _npts = []
            if isinstance(_obj, Generic.leader.Leader):
                _leader = True
            for _pt in _obj.getPoints():
                _pid = id(_pt)
                if _pid in _newobjs:
                    _npt= _newobjs[_pid]
                else:
                    _x, _y = _pt.getCoords()
                    _npt = to_layer.find('point', _x, _y)
                    if _npt is None:
                        _npt = _pt.clone()
                        to_layer.addObject(_npt)
                    _newobjs[_pid] = _npt
                _npts.append(_npt)
            _newobj = _obj.clone()
            if _leader:
                _newobj.setP1(_npts[0])
                _newobj.setP2(_npts[1])
                _newobj.setP3(_npts[2])
            else:
                for _i in range(len(_npts)):
                    _newobj.setPoint(_i, _npts[_i])
            _newobj.reset()
            to_layer.addObject(_newobj)
            _newobjs[_oid] = _newobj
        elif isinstance(_obj, (Generic.hcline.HCLine,
                               Generic.vcline.VCLine,
                               Generic.acline.ACLine)):
            _pt = _obj.getLocation()
            _pid = id(_pt)
            if _pid in _newobjs:
                _npt = _newobjs[_pid]
            else:
                _x, _y = _pt.getCoords()
                _npt = to_layer.find('point', _x, _y)
                if _npt is None:
                    _npt = _pt.clone()
                    to_layer.addObject(_npt)
                _newobjs[_pid] = _npt
            if isinstance(_obj, Generic.hcline.HCLine):
                _newobj = Generic.hcline.HCLine(_npt)
            elif isinstance(_obj, Generic.vcline.VCLine):
                _newobj = Generic.vcline.VCLine(_npt)
            elif isinstance(_obj, Generic.acline.ACLine):
                _newobj = Generic.acline.ACLine(_npt, _obj.getAngle())
            else:
                raise TypeError, "Unexpected dimension type: " + type(_obj)
            to_layer.addObject(_newobj)
            _newobjs[_oid] = _newobj
        elif isinstance(_obj, (Generic.circle.Circle,
                               Generic.arc.Arc,
                               Generic.ccircle.CCircle)):
            _pt = _obj.getCenter()
            _pid = id(_pt)
            if _pid in _newobjs:
                _npt = _newobjs[_pid]
            else:
                _x, _y = _pt.getCoords()
                _npt = to_layer.find('point', _x, _y)
                if _npt is None:
                    _npt = _pt.clone()
                    to_layer.addObject(_npt)
                _newobjs[_pid] = _npt
            if isinstance(_obj, Generic.ccircle.CCircle):
                _newobj = Generic.ccircle.CCircle(_npt, _obj.getRadius())
            else:
                #
                # arc endpoints will get added because they are
                # in the _objdict dictionary
                #
                _newobj = _obj.clone()
                _newobj.setCenter(_npt)
                _newobj.reset()
            to_layer.addObject(_newobj)
            _newobjs[_oid] = _newobj
        elif isinstance(_obj, (Generic.segjoint.Chamfer,
                               Generic.segjoint.Fillet)):
            _s1, _s2 = _obj.getSegments()
            _is1 = id(_s1)
            _is2 = id(_s2)
            if _is1 in _newobjs and _is2 in _newobjs:
                _ns1 = _newobjs[_is1]
                _ns2 = _newobjs[_is2]
                if isinstance(_obj, Generic.segjoint.Chamfer):
                    _newobj = Generic.segjoint.Chamfer(_ns1, _ns2,
                                                       _obj.getLength())
                else:
                    _newobj = Generic.segjoint.Fillet(_ns1, _ns2,
                                                      _obj.getRadius())
                _newobj.setStyle(_obj.getStyle())
                _newobj.setLinetype(_obj.getLinetype())
                _newobj.setColor(_obj.getColor())
                _newobj.setThickness(_obj.getThickness())
                to_layer.addObject(_newobj)
            else:
                _sjoints.append(_obj)
        else:
            print "Skipping object type %s in objdict" % type(_obj)
    #
    # handle any chamfers and fillets now that all the segments
    # they join should have cloned copies in the 'to' layer
    #
    if len(_sjoints):
        for _obj in _sjoints:
            _s1, _s2 = _obj.getSegments()
            _is1 = id(_s1)
            if _is1 not in _newobjs:
                raise KeyError, "Segjoint s1 segment not transfered"
            _is2 = id(_s2)
            if _is2 not in _newobjs:
                raise KeyError, "Segjoint s2 segment not transfered"
            _ns1 = _newobjs[_is1]
            _ns2 = _newobjs[_is2]
            if isinstance(_obj, Generic.segjoint.Chamfer):
                _newobj = Generic.segjoint.Chamfer(_ns1, _ns2,
                                                   _obj.getLength())
            else:
                _newobj = Generic.segjoint.Fillet(_ns1, _ns2,
                                                  _obj.getRadius())
            _newobj.setStyle(_obj.getStyle())
            _newobj.setLinetype(_obj.getLinetype())
            _newobj.setColor(_obj.getColor())
            _newobj.setThickness(_obj.getThickness())
            to_layer.addObject(_newobj)
    #
    # adjust dimensions attached to objects that may have been
    # transfered between the layers
    #
    if len(_dimobjs):
        _adjust_dimensions(_dimobjs, _newobjs, to_layer)
    #
    # transfer any dimensions and text blocks
    #
    # text blocks do not reference any points so they can be transfered
    # at will, but as dimensions references points, circle, or arcs, moving
    # them has to be done by first deleting them from the layer they
    # currently sit in (and thusly diconnecting them from the points or
    # circlular objects they use) and then adding them to the new layer
    # if they are first added to the new layer and then deleted from the
    # old, the points and circles dimensions refer to can lose track of the
    # fact that there is a dimension bound to themselves
    #
    if len(_dtobjs):
        for _obj in _dtobjs:
            from_layer.delObject(_obj)
            to_layer.addObject(_obj)
    #
    # now remove the objects from the layer they where they
    # are currently stored
    #
    _remove_objects(_objdict, from_layer)
