# -*- coding: utf-8 -*-
"""
/***************************************************************************
 QEsg_06Export
                                 A QGIS plugin
 Plugin para Calculo de redes de esgotamento sanitario
                              -------------------
        begin                : 2016-03-15
        git sha              : $Format:%H$
        copyright            : (C) 2016 by Jorge Almerio
        email                : jorgealmerio@yahoo.com.br
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program 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.                                   *
 *                                                                         *
 ***************************************************************************/
"""
from qgis.core import *
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from qgis.utils import *
import os.path
from QEsg_00Model import *
from QEsg_03Dimensionamento import *

import qgis

class QEsg_06Export:
    def __init__(self):
        self.DimensClasse=QEsg_03Dimens()
        try:
            self.dirname, filename = os.path.split(os.path.abspath(__file__))
            sys.path.append(self.dirname)
            from dxfwrite import DXFEngine as dxf
        except ImportError:
            from dxfwrite import DXFEngine as dxf
        self.dxf=dxf
        self.dirname, filename = os.path.split(os.path.abspath(__file__))
        sys.path.append(self.dirname)

    def run(self):
        dxfPath=os.path.join(self.dirname,'test.dxf')#substituir por filedialog
        dxf=self.dxf
        drawing = dxf.drawing(dxfPath)
        self.drawing=drawing
        drawing.header['$INSUNITS'] = 6 #set units to meters
        drawing.header['$AUPREC'] = 6 #set angles precision
        self.criaRede()
#         drawing.add(dxf.line((0, 0), (10, 0), color=7))
#         drawing.add_layer('TEXTLAYER', color=2)
#         drawing.add(dxf.text('Test', insert=(0, 0.2), layer='TEXTLAYER'))
        drawing.save()
        aviso="Saved to:" + dxfPath
        iface.messageBar().pushMessage("QEsg:", aviso, level=QgsMessageBar.INFO, duration=4)

    def criaRede(self):
        vLayer=self.DimensClasse.PegaQEsgLayer('PIPES')
        if vLayer==False:
            aviso=QCoreApplication.translate('QEsg',u'Layer Tipo \'PIPES\' indefinido ou não encontrado!')
            iface.messageBar().pushMessage("QEsg:", aviso, level=QgsMessageBar.WARNING, duration=4)
            return False
        from dxfwrite.const import CENTER
        drawing=self.drawing
        dxf=self.dxf
        e=vLayer.extent()
        drawing.header['$EXTMIN'] = (e.xMinimum(),e.yMinimum(),0) #Lower left corner
        drawing.header['$EXTMAX'] = (e.xMaximum(),e.yMaximum(),0) #Upper Right corner
        for feat in vLayer.getFeatures():
            polilinha=feat.geometry().asPolyline()
            v1=polilinha[0]
            v2=polilinha[1]
            line = dxf.line(v1,v2)

            pos,rot=self.textIns(v1,v2)
            texto=feat['DC_ID']
            text = dxf.text(texto,height=6,rotation=rot,halign=CENTER,alignpoint=pos)

            drawing.add(line)
            drawing.add(text)
    def textIns(self,v1,v2):
        azim=v1.azimuth(v2)
        if azim<0:
            azim+=360
        rot=90.-azim
        if 180<=azim<360:
            rot-=180
        pos=self.mid(v1,v2)
        return pos,rot
    def mid(self, pt1, pt2):
       x = (pt1.x() + pt2.x())/2
       y = (pt1.y() + pt2.y())/2
       return QgsPoint(x,y)