'''

@author: olivier.massot, sept. 2018
'''
import shapefile

POINT = 1
POLYLINE = 3
POLYGON = 5
SHAPE_NAMES = {0: "(AUCUN)", 
               1: "POINT", 
               3:"POLYLIGNE", 
               5:"POLYGONE",
               8: "MULTI-POINT",
               11: "POINT-Z",
               13: "POLYLIGNE-Z",
               15: "POLYGONE-Z",
               18: "MULTIPOINT-Z",
               21: "POINT-M",
               23: "POLYLIGNE-M",
               25: "POLYGONE-M",
               28: "MULTIPOINT-M",
               31: "MULTI-PATCH",
               }


class ShapeError(IOError): 
    pass
class SridError(IOError): 
    pass

class ShapeFile():
    def __init__(self, path_, srid=None):
        self.path_ = path_
        self.srid = srid
    
    def __enter__(self):
        if not self.path_.isfile():
            raise FileNotFoundError("Fichier introuvable")
     
        try:
            self.sf = shapefile.Reader(self.path_)
        except shapefile.ShapefileException:
            raise ShapeError("Fichier Shape illisible")
        
        if not self.sf.shapeType in (POINT, POLYLINE, POLYGON):
            raise ShapeError("Type de géométrie non reconnue")

#         if self.srid is not None:
#             if not self.sf.srid == self.srid:
#                 raise SridError("Le SRID du fichier doit être '{}'".format(self.srid))

        return self
    
    def shape(self):
        return self.sf.shapeType
    
    def fields(self):
        return [f[0] for f in self.sf.fields if f[0] != 'DeletionFlag']
        
    def records(self):
        for record in self.sf.shapeRecords():
            yield record
        
    def __exit__(self, exc_type, exc_val, exc_tb):
        del self.sf