from osgeo import ogr, osr


from rosreestrXml.ui.tools.KPT.kptTools.KptBound import createDocumentsStruct, addAtributDocuments


class SpatialObjPolyLine:
    __cs_prj4=None
    __str_styleMi=None
    __poinst=None
    __reverseXY=True
    __name_layer="квартал"
    __count=1
    __nameProcess = "Импорт кадастрового квартала"
    '''
    cs=coordSys proj4
    point = list point KPT
    attr = ftribute KPT
    
    '''
    def __init__(self,cs,points,attr:list,mi_style:str=None,reversXY=True):

        self.__cs_prj4=cs
        self.__poinst=points
        self.__str_styleMi=mi_style
        self.__str_styleMi=''
        self.__attr=attr
        self.__reverseXY=reversXY
        #self.__createStruct()
        self.__struct=SpatialObjPolyLine.getStruct()
    def setProperty(self,propery):
        self.__propert=propery
        self.__cs_prj4=propery['cs']
    def setAttribute(self,att):
        self.__attr=att
    def __createStruct(self):
        self.__struct=[]
        field_caD={}
        field_caD['name']='КадНомер'
        field_caD['type'] = ogr.OFTString
        field_caD['width'] = 50
        self.__struct.append(field_caD)
        field_1={}
        field_1['name']="код_документа"
        field_1['type']=ogr.OFTString
        field_1['width']=20
        self.__struct.append(field_1)
        field_2 = {}
        field_2['name'] = "название"
        field_2['type'] = ogr.OFTString
        field_2['width'] = 500
        self.__struct.append(field_2)
        field_3 = {}
        field_3['name'] = "серия_документа"
        field_3['type'] = ogr.OFTString
        field_3['width'] = 45
        self.__struct.append(field_3)
        field_4={}
        field_4['name']='Номер_документа'
        field_4['type']= ogr.OFTString
        field_4['width'] = 45
        field_date={}
        field_date['name']='Дата_выдачи'
        field_date['type']=ogr.OFTString
        field_date['width'] = 24
        self.__struct.append(field_date)
        if self.__str_styleMi is not None:
            field_style={}
            field_style = {}
            field_style['name'] = "MI_STYLE"
            field_style['type'] = ogr.OFTString
            field_style['width'] = 120
            self.__struct.append(field_style)

    @staticmethod
    def getStruct():
        struct = []
        field_caD = {}
        field_caD['name'] = 'КадНомер'
        field_caD['type'] = ogr.OFTString
        field_caD['width'] = 50
        struct.append(field_caD)
        struct.extend(createDocumentsStruct())
        field_style={}
        field_style = {}
        field_style['name'] = "MI_STYLE"
        field_style['type'] = ogr.OFTString
        field_style['width'] = 120
        struct.append(field_style)
        return struct
    @property
    def Count(self):
        return self.__count

    @property
    def NameProcess(self):
        return self.__nameProcess

    @property
    def NameLayer(self):
        return self.__name_layer
    def CreateLayer(self,ds,createNewLayer=False):
        layer = None
        if not createNewLayer:
            layer = ds.GetLayer(self.__name_layer)
            if layer is not None:
                return layer
        srs= osr.SpatialReference()
        #srs.ImportFromProj4(self.__cs_prj4)
        srs.ImportFromWkt(self.__cs_prj4)
        layer = ds.CreateLayer(self.__name_layer, srs, geom_type=ogr.wkbUnknown)
        for fld in self.__struct:
            # create fields
            field_cur = ogr.FieldDefn(fld['name'],fld['type'])
            type_field=fld['type']
            if fld['type']==ogr.OFTString:
                field_cur.SetWidth(fld['width'])
            layer.CreateField(field_cur)
        return layer
    def Write(self,layer,dbCatalog=None,dbDocument=None):
        ''' Получаем стиль из базы'''
        mi_style = dbCatalog.GetStyle('kpt_10_style', 'SpatialData')
        if mi_style[0] is None:
            print(mi_style[1])
            str_mi_style = 'Pen (2, 6, 16711680) Brush (1, 16777215, 16777215)'
        else:
            str_mi_style = mi_style[0]
        poly=self.__createPolygon()
        feature = ogr.Feature(layer.GetLayerDefn())
        #curent_att=self.__attr.copy()

        if self.__str_styleMi is not None:
            feature.SetField('MI_STYLE',str_mi_style)
        if (self.__attr is not None) and (len(self.__attr)>0):
            for att in self.__attr:
                try:
                    feature.SetField(att['name'],att['value'])
                except:
                    pass
        if poly is not None:
            feature.SetGeometry(poly)
        layer.CreateFeature(feature)
        poly=None
        feature=None
        return
    def WriteItem(self,i,layer,kptCatalog,mapCatalog):
        poly = self.__createPolygon()
        feature = ogr.Feature(layer.GetLayerDefn())
        if self.__str_styleMi is not None:
            feature.SetField('MI_STYLE', self.__str_styleMi)
        if (self.__attr is not None) and (len(self.__attr) > 0):
            for att in self.__attr:
                feature.SetField(att['name'], att['value'])
        if poly is not None:
            feature.SetGeometry(poly)
        layer.CreateFeature(feature)
        poly = None
        feature = None
        mapCatalog.addLayerInfoInMapCataalog(layer, self.__propert['cs_mi'])
        return
    def __createPolygon(self):
        polygons=[]
        for poly_points in self.__poinst:
            poly=self.__createPolygonLocal(poly_points)
            polygons.append(poly)
        if len(polygons)==1:
            return polygons[0]
        return None
    def __createPolygonLocal(self,points):
        # Create ring
        ring = ogr.Geometry(ogr.wkbLinearRing)
        for pnt in points:
            if self.__reverseXY:
                x = float(pnt.Y)
                y = float(pnt.X)
            else:
                x=float(pnt.X)
                y=float(pnt.Y)
            ring.AddPoint(x,y)
        # Create polygon
        poly = ogr.Geometry(ogr.wkbPolygon)
        poly.AddGeometry(ring)
        return poly


