import sys
#import collections
# custom imports
from atom import *

class PDBFile:
    def getContent(self, filename):
        with open(filename) as f:
            return(f.readlines())

    def getHeader(self):
        #Metadata = collections.namedtuple("Metadata", ["header", "compound", "source", "author"])
        Metadata = {}
        for line in self.rawLines:
            # no need to continue if meta are complete
            if(len(Metadata) <4):
                if(line[0:10] == "HEADER    "):
                    Metadata['header']=line
                elif(line[0:10] == "COMPND   2"):
                    Metadata['compound']=line
                elif(line[0:10] == "SOURCE   2"):
                    Metadata['source']=line
                elif(line[0:10] == "AUTHOR    "):
                    Metadata['author']=line
            else:
                # if meta are complete, stop parsing
                break     
        return(Metadata)

    def getAtoms(self):
        self.atoms = []
        self.residues = []
        temp_atoms = []
        for line in self.rawLines:
            if line.startswith("ATOM" or "HETATM"):
                atom = Atom(atom_id = int(line[6:11].strip()),
                            atom_name = line[12:16].strip(),
                            res_name = line[17:20].strip(),
                            chain_id = line[21:22].strip(),
                            res_seq_nb = int(line[22:26].strip()),
                            coordinates = [float(line[30:38].strip()),
                                     float(line[38:46].strip()),
                                     float(line[46:54].strip()),
                            ])
                self.atoms.append(atom)
                # get the current indice of atom
                i = self.atoms.index(atom)
                # if this is a brand new residue
                if(len(self.atoms)>1
                   and atom.res_seq_nb != self.atoms[i-1].res_seq_nb):
                    self.residues.append(Residue(temp_atoms))
                    temp_atoms=[]
                temp_atoms.append(atom)
        # last residue
        self.residues.append(Residue(temp_atoms))
       
    def __init__(self, filename):
        self.rawLines = self.getContent(filename)
        self.Metadata = self.getHeader()
        self.getAtoms()
        for elem in self.Metadata :    
            print(self.Metadata[elem], end="")


if __name__ == "__main__":
    if(len(sys.argv)<2):
        print("Not enough arguments! Run with --help to learn more about proper"
              "call structure and parameters.")
    else:
        pdbFile = PDBFile(sys.argv[1])
        print(pdbFile.residues[15].atoms["C"].coord_x)
