import numpy as np

class Hgrid:

    def __init__(self):
        pass

    def read_hgrid(self, fname, *args):
        with open(fname, 'r') as fid:
            lines=fid.readlines()
        
        #get NE, NP
        line=np.array(lines[1].split()[0:2]).astype('int')
        self.NE=line[0]
        self.NP=line[1]

        #read x, y, and depth
        line=[]
        for i in np.arange(self.NP):
            line.append(np.array(lines[2+i].split()[1:4]))
        line=np.array(line).astype('float')
        self.x=line[:,0]
        self.y=line[:,1]
        self.depth=line[:,2]

        if len(lines) < (2+self.NP+self.NE):
            return

        #read elements
        line=[]
        for i in np.arange(self.NE):
            line.append(lines[2+self.NP+i].split())
        line=np.array([s if len(s)==6 else [*s,'-1'] for s in line])
        line=line.astype('int')

        self.i34=line[:,1]
        self.elnode=line[:,2:]-1

        if len(lines) < (4+self.NP+self.NE):
            return

        #read obnd 
        nline=2+self.NP+self.NE
        line=np.array(lines[nline].split()[0]).astype('int')
        self.nob=line
        nline=nline+2

        self.nobn=[]
        self.iobn=[]
        for i in np.arange(self.nob):
            line=np.array(lines[nline].split()[0]).astype('int')
            self.nobn.append(line)
            line=[]
            for m in np.arange(self.nobn[i]):
                line.append(lines[nline+m+1].split()[0])
            self.iobn.append(np.array(line).astype('int')-1)
            #self.iobn.append(line)
            nline=nline+self.nobn[i]+1
        self.nobn=np.array(self.nobn)
        self.iobn=np.array(self.iobn,dtype='O')
        if len(self.iobn)==1: self.iobn=self.iobn.astype('int')

        #read lbnd
        line=np.array(lines[nline].split()[0]).astype('int')
        self.nlb=line
        nline=nline+2

        self.nlbn=[]
        self.ilbn=[]
        self.island=[]
        for i in np.arange(self.nlb):
            line=np.array(lines[nline].split()[0]).astype('int')
            self.nlbn.append(line)
            line=[]
            for m in np.arange(self.nlbn[i]):
                line.append(lines[nline+m+1].split()[0])
            self.ilbn.append(np.array(line).astype('int')-1)

            #update island flag method
            if line[0]==line[-1]:
                self.island.append(1)
            else:
                self.island.append(0)

            nline=nline+self.nlbn[i]+1

        self.island=np.array(self.island)
        self.nlbn=np.array(self.nlbn)
        self.ilbn=np.array(self.ilbn,dtype='O')
        if len(self.ilbn)==1: self.ilbn=self.ilbn.astype('int')

        return self.iobn[0], self.ilbn[0]
        #print(self.ilbn[0])

    #@property
    #def ocean_boundaries(self):
    #    return self.iobn

    #@property
    #def land_boundaries(self):
    #    return self.ilbn[0]
