from osgeo import ogr, osr


class SpatialDataKvartal:
    __name='границы_кварталов'
    __nameProcess='Импорт границ кварталов'
    def __init__(self,tagSpatial,cadastralNumber,properties):
        if tagSpatial is None:
            return
        self.__xmlSpatial=tagSpatial
        self.__CadastralNumber=cadastralNumber
        self.__properties=properties
        self.__cs_wkt=properties['cs']
        self.__reverseXY=properties['reverseXY']
        #self.__mi_style=properties['spatial']['style']
        self.__mi_style=''
        self.__geoObj=None
        self.__build()

    @property
    def NameLayer(self):
        return self.__name

    @property
    def NameProcess(self):
        return self.__nameProcess
    def __build(self):
        xml_polygons=self.__xmlSpatial.entity_spatial.spatials_elements.spatial_element
        #.ordinates
        polygons=[]
        linesRings=[]
        for xml_poly in xml_polygons :
            geo_poly=  ogr.Geometry(ogr.wkbPolygon)
            lineRing=ogr.Geometry(ogr.wkbLinearRing)
            for xmlPnt in xml_poly.ordinates.ordinate:
                if self.__reverseXY:
                    x = xmlPnt.y
                    y = xmlPnt.x
                else:
                    x=xmlPnt.x
                    y=xmlPnt.y
                lineRing.AddPoint(float(x),float(y))
            geo_poly.AddGeometry(lineRing)
            linesRings.append(lineRing)
            polygons.append(geo_poly)
        if len(polygons)==1:
            self.__geoObj=polygons[0]
            return
        #self.__geoObj= ogr.Geometry(ogr.wkbMultiPolygon)
        self.__geoObj = ogr.Geometry(ogr.wkbPolygon)
        for poly in linesRings:
            self.__geoObj.AddGeometry(poly)
        return
    @staticmethod
    def struct():
        struct = []

        struct.append({'name': 'кадастровый_номер', 'type': ogr.OFTString, 'width': 22})

        return struct
    def CreateLayer(self,ds,createNewLayer=True):
        srs = osr.SpatialReference()
        srs.ImportFromWkt(self.__cs_wkt)
        layer=None
        if not createNewLayer:
            layer=ds.GetLayer(self.__name)
            if layer is not None:
                return layer

        layer = ds.CreateLayer(self.__name, srs, geom_type=ogr.wkbPolygon)
        struct_layer=SpatialDataKvartal.struct()
        for fld in struct_layer:
            # 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)
        if self.__mi_style is not None:
            field_cur = ogr.FieldDefn("MI_STYLE", ogr.OFTString)
            field_cur.SetWidth(128)
            layer.CreateField(field_cur)
        return layer
    def Write(self,layer,dbDictionary=None,mapCatalog=None):
        if self.__geoObj is None:
            return
        ''' Получаем стиль из базы'''

        mi_style = dbDictionary.GetStyle('kpt_11_style', 'bound_kvartal')
        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]
        att = []

        att.append({'name': 'кадастровый_номер', 'value': self.__CadastralNumber})
        if self.__mi_style is not None:
            att.append({'name': 'MI_STYLE', 'value': str_mi_style})
        feature = ogr.Feature(layer.GetLayerDefn())
        for atr_item in att:
            # print(atr_item['name'])
            # print(atr_item['value'])
            feature.SetField(atr_item['name'], atr_item['value'])
        feature.SetGeometry(self.__geoObj)

        layer.CreateFeature(feature)
        self.__geoObj=None
        feature=None
        mapCatalog.addLayerInfoInMapCataalog(layer,self.__properties['cs_mi'])
        layer=None