#
# 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
#
#
# code to handle moving objects
#

from PythonCAD.Generic.point import Point
from PythonCAD.Generic.segment import Segment
from PythonCAD.Generic.circle import Circle
from PythonCAD.Generic.arc import Arc
from PythonCAD.Generic.hcline import HCLine
from PythonCAD.Generic.vcline import VCLine
from PythonCAD.Generic.acline import ACLine
from PythonCAD.Generic.segjoint import Chamfer, Fillet
from PythonCAD.Generic.cline import CLine
from PythonCAD.Generic.ccircle import CCircle
from PythonCAD.Generic.leader import Leader
from PythonCAD.Generic.polyline import Polyline
from PythonCAD.Generic.text import TextBlock
from PythonCAD.Generic.dimension import Dimension
from PythonCAD.Generic.dimension import LinearDimension
from PythonCAD.Generic.dimension import AngularDimension
from PythonCAD.Generic.layer import Layer

def _adjust_dimensions(layer, point, newpoint):
    _users = point.getUsers()
    for _uref in _users:
        _user = _uref()
        if _user is not None:
            if isinstance(_user, Dimension):
                if isinstance(_user, LinearDimension):
                    _l1, _l2 = _user.getDimLayers()
                    _p1, _p2 = _user.getDimPoints()
                    if _l1 is layer and _p1 is point:
                        _user.setP1(layer, newpoint)
                    elif _l2 is layer and _p2 is point:
                        _user.setP2(layer, newpoint)
                elif isinstance(_user, AngularDimension):
                    _vl, _l1, _l2 = _user.getDimLayers()
                    _vp, _p1, _p2 = _user.getDimPoints()
                    if _vl is layer and _vp is point:
                        _user.setVertexPoint(layer, newpoint)
                    elif _l1 is layer and _p1 is point:
                        _user.setP1(layer, newpoint)
                    elif _l2 is layer and _p2 is point:
                        _user.setP2(layer, newpoint)
                else:
                    raise TypeError, "Unknown dimension: " + `_user`

def _move_point(layer, point, dx, dy):
    _x, _y = point.getCoords()
    _nx = _x + dx
    _ny = _y + dy
    _np = layer.find('point', _nx, _ny)
    if _np is None:
        _np = Point(_nx, _ny)
        layer.addObject(_np)
    _adjust_dimensions(layer, point, _np)
    layer.delObject(point)

def _move_segment(layer, segment, dx, dy):
    _p1, _p2 = segment.getEndpoints()
    _x, _y = _p1.getCoords()
    _nx = _x + dx
    _ny = _y + dy
    _np1 = layer.find('point', _nx, _ny)
    if _np1 is None:
        _np1 = Point(_nx, _ny)
        layer.addObject(_np1)
    _adjust_dimensions(layer, _p1, _np1)
    _x, _y = _p2.getCoords()
    _nx = _x + dx
    _ny = _y + dy
    _np2 = layer.find('point', _nx, _ny)
    if _np2 is None:
        _np2 = Point(_nx, _ny)
        layer.addObject(_np2)
    _adjust_dimensions(layer, _p2, _np2)
    segment.setP1(_np1)
    segment.setP2(_np2)
    layer.delObject(_p1)
    layer.delObject(_p2)

def _move_arc(layer, arc, dx, dy):
    _cp = arc.getCenter()
    _x, _y = _cp.getCoords()
    _ep1, _ep2 = arc.getEndpoints()
    _lp1 = layer.find('point', _ep1[0], _ep1[1])
    assert _lp1 is not None, "Lost arc first endpoint"
    _lp2 = layer.find('point', _ep2[0], _ep2[1])
    assert _lp2 is not None, "Lost arc second endpoint"
    _nx = _x + dx
    _ny = _y + dy
    _ncp = layer.find('point', _nx, _ny)
    if _ncp is None:
        _ncp = Point(_nx, _ny)
        layer.addObject(_ncp)
    for _ep in arc.getEndpoints():
        _ex, _ey = _ep
        _nx = _ex + dx
        _ny = _ey + dy
        _lp = layer.find('point', _nx, _ny)
        if _lp is None:
            _lp = Point(_nx, _ny)
            layer.addObject(_lp)
    arc.setCenter(_ncp)        
    _adjust_dimensions(layer, _cp, _ncp)
    layer.delObject(_cp)
    _lp1.freeUser(arc)
    layer.delObject(_lp1)
    _lp2.freeUser(arc)
    layer.delObject(_lp2)

def _move_circle(layer, circle, dx, dy): # moves circle and ccircles
    _cp = circle.getCenter()
    _x, _y = _cp.getCoords()
    _nx = _x + dx
    _ny = _y + dy
    _ncp = layer.find('point', _nx, _ny)
    if _ncp is None:
        _ncp = Point(_nx, _ny)
        layer.addObject(_ncp)
    _adjust_dimensions(layer, _cp, _ncp)
    circle.setCenter(_ncp)
    layer.delObject(_cp)

def _move_leader(layer, leader, dx, dy):
    _p1, _p2, _p3 = leader.getPoints()
    _x, _y = _p1.getCoords()
    _nx = _x + dx
    _ny = _y + dy
    _np1 = layer.find('point', _nx, _ny)
    if _np1 is None:
        _np1 = Point(_nx, _ny)
        layer.addObject(_np1)
    _adjust_dimensions(layer, _p1, _np1)
    _x, _y = _p2.getCoords()
    _nx = _x + dx
    _ny = _y + dy
    _np2 = layer.find('point', _nx, _ny)
    if _np2 is None:
        _np2 = Point(_nx, _ny)
        layer.addObject(_np2)
    _adjust_dimensions(layer, _p2, _np2)
    _x, _y = _p3.getCoords()
    _nx = _x + dx
    _ny = _y + dy
    _np3 = layer.find('point', _nx, _ny)
    if _np3 is None:
        _np3 = Point(_nx, _ny)
        layer.addObject(_np3)
    _adjust_dimensions(layer, _p3, _np3)
    leader.setP1(_np1)
    leader.setP2(_np2)
    leader.setP3(_np3)
    layer.delObject(_p1)
    layer.delObject(_p2)
    layer.delObject(_p3)

def _move_polyline(layer, polyline, dx, dy):
    _pts = polyline.getPoints()
    _npts = []
    for _pt in _pts:
        _x, _y = _pt.getCoords()
        _nx = _x + dx
        _ny = _y + dy
        _np = layer.find('point', _nx, _ny)
        if _np is None:
            _np = Point(_nx, _ny)
            layer.addObject(_np)
        _adjust_dimensions(layer, _pt, _np)
        _npts.append(_np)
    for _i in range(len(_npts)):
        polyline.setPoint(_i, _npts[_i])
    for _pt in _pts:
        layer.delObject(_pt)

def _move_segjoint(layer, segjoint, dx, dy):
    _s1, _s2 = segjoint.getSegments()
    _move_segment(layer, _s1, dx, dy)
    _move_segment(layer, _s2, dx, dy)

def _move_spcline(layer, spcline, dx, dy):
    _p = spcline.getLocation()
    _x, _y = _p.getCoords()
    _nx = _x + dx
    _ny = _y + dy
    _np = layer.find('point', _nx, _ny)
    if _np is None:
        _np = Point(_nx, _ny)
        layer.addObject(_np)
    _adjust_dimensions(layer, _p, _np)
    spcline.setLocation(_np)
    layer.delObject(_p)

def _move_cline(layer, cline, dx, dy):
    _p1, _p2 = cline.getKeypoints()
    _x, _y = _p1.getCoords()
    _nx = _x + dx
    _ny = _y + dy
    _np1 = layer.find('point', _nx, _ny)
    if _np1 is None:
        _np1 = Point(_nx, _ny)
        layer.addObject(_np1)
    _adjust_dimensions(layer, _p1, _np1)
    _x, _y = _p2.getCoords()
    _nx = _x + dx
    _ny = _y + dy
    _np2 = layer.find('point', _nx, _ny)
    if _np2 is None:
        _np2 = Point(_nx, _ny)
        layer.addObject(_np2)
    _adjust_dimensions(layer, _p2, _np2)
    cline.setP1(_np1)
    cline.setP2(_np2)
    layer.delObject(_p1)
    layer.delObject(_p2)

def _move_dimension(dim, dx, dy):
    _x, _y = dim.getLocation()
    _nx = _x + dx
    _ny = _y + dy
    dim.setLocation(_nx, _ny)

def move_objects(layer, objlist, dx, dy):
    """Move objects in a layer.

move_objects(layer, objlist, dx, dy)

layer; The layer in which all the objects are located
objlist: The list of objects to move. This argument must be a list
dx: The displacement along the x-axis
dy: The displacement along the y-axix
    """
    if not isinstance(layer, Layer):
        raise TypeError, "Invalid layer: " + str(layer)
    if not isinstance(objlist, list):
        raise TypeError, "Invalid object list: " + str(objlist)
    _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 and abs(_dy) < 1e-10:
        return
    _objlist = []
    _objdict = {}
    for _obj in objlist:
        _lobj = layer.findObject(_obj)
        if _lobj is not _obj:
            raise ValueError, "Object not found in layer: " + str(_obj)
        _objdict[id(_obj)] = True
        _objlist.append(_obj)
    for _obj in _objlist:
        if isinstance(_obj, Segment):
            _p1, _p2 = _obj.getEndpoints()
            _pid = id(_p1)
            if _pid in _objdict:
                _objdict[_pid] = False
            _pid = id(_p2)
            if _pid in _objdict:
                _objdict[_pid] = False
        elif isinstance(_obj, (Circle, Arc, CCircle)):
            _cp = _obj.getCenter()
            _cpid = id(_cp)
            if _cpid in _objdict:
                _objdict[_cpid] = False
            if isinstance(_obj, Arc):
                for _ep in _obj.getEndpoints():
                    _lp = layer.find('point', _ep[0], _ep[1])
                    if _lp is None:
                        raise ValueError, "Lost arc endpoint: " + str(_ep)
                    _pid = id(_lp)
                    if _pid in _objdict:
                        _objdict[_pid] = False
        elif isinstance(_obj, (HCLine, VCLine, ACLine)):
            _p = _obj.getLocation()
            _pid = id(_p)
            if _pid in _objdict:
                _objdict[_pid] = False
        elif isinstance(_obj, CLine):
            _p1, _p2 = _obj.getKeypoints()
            _pid = id(_p1)
            if _pid in _objdict:
                _objdict[_pid] = False
            _pid = id(_p2)
            if _pid in _objdict:
                _objdict[_pid] = False
        elif isinstance(_obj, (Leader, Polyline)):
            for _pt in _obj.getPoints():
                _pid = id(_pt)
                if _pid in _objdict:
                    _objdict[_pid] = False
        elif isinstance(_obj, (Chamfer, Fillet)):
            _s1, _s2 = _obj.getSegments()
            _sid = id(_s1)
            if _sid in _objdict:
                _objdict[_sid] = False
            _p1, _p2 = _s1.getEndpoints()
            _pid = id(_p1)
            if _pid in _objdict:
                _objdict[_pid] = False
            _pid = id(_p2)
            if _pid in _objdict:
                _objdict[_pid] = False
            _sid = id(_s2)
            if _sid in _objdict:
                _objdict[_sid] = False
            _p1, _p2 = _s2.getEndpoints()
            _pid = id(_p1)
            if _pid in _objdict:
                _objdict[_pid] = False
            _pid = id(_p2)
            if _pid in _objdict:
                _objdict[_pid] = False
        else:
            pass
    for _obj in _objlist:
        if _objdict[id(_obj)]:
            if isinstance(_obj, Point):
                _move_point(layer, _obj, _dx, _dy)
            elif isinstance(_obj, Segment):
                _move_segment(layer, _obj, _dx, _dy)
            elif isinstance(_obj, Arc):
                _move_arc(layer, _obj, _dx, _dy)
            elif isinstance(_obj, (Circle, CCircle)):
                _move_circle(layer, _obj, _dx, _dy)
            elif isinstance(_obj, Leader):
                _move_leader(layer, _obj, _dx, _dy)
            elif isinstance(_obj, Polyline):
                _move_polyline(layer, _obj, _dx, _dy)
            elif isinstance(_obj, (Chamfer, Fillet)):
                _move_segjoint(layer, _obj, _dx, _dy)
            elif isinstance(_obj, (HCLine, VCLine, ACLine)):
                _move_spcline(layer, _obj, _dx, _dy)
            elif isinstance(_obj, CLine):
                _move_cline(layer, _obj, _dx, _dy)
            elif isinstance(_obj, Dimension):
                _move_dimension(_obj, _dx, _dy)
            elif isinstance(_obj, TextBlock):
                _x, _y = _obj.getLocation()
                _nx = _x + _dx
                _ny = _y + _dy
                _obj.setLocation(_nx, _ny)
            else:
                pass
