'''

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

POINT = 1
POLYLINE = 3
POLYGON = 5
SHAPE_NAMES = {1: "POINT", 3:"POLYLIGNE", 5:"POLYGONE"}

class ShapeError(IOError): pass

class ShapeFile():
    def __init__(self, path_):
        self.path_ = path_
    
    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")

        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