# coding: utf-8
"""
Gro file format
defined in http://manual.gromacs.org/current/online/gro.html
"""


def hook7(lattice):
    lattice.logger.info("Hook7: Output in Gromacs format.")
    lattice.logger.info("  Total number of atoms: {0}".format(len(lattice.atoms)))
    if len(lattice.atoms) > 99999:
        lattice.logger.warn("  Gromacs fixed format cannot deal with atoms more than 99999. Residue number and atom number are faked.")
    cellmat = lattice.repcell.mat
    s = ""
    s += "Generated by GenIce https://github.com/vitroid/GenIce \n"
    s += "{0}\n".format(len(lattice.atoms))
    molorder = 0
    for i in range(len(lattice.atoms)):
        resno, resname, atomname, position, order = lattice.atoms[i]
        if resno == 0:
            molorder += 1
        if len(lattice.atoms) > 99999:
            s += "{0:5d}{1:5s}{2:>5s}{3:5d}{4:8.3f}{5:8.3f}{6:8.3f}\n".format(9999,resname, atomname, 9999,position[0],position[1],position[2])
        else:
            s += "{0:5d}{1:5s}{2:>5s}{3:5d}{4:8.3f}{5:8.3f}{6:8.3f}\n".format(molorder,resname, atomname, i+1,position[0],position[1],position[2])
    if cellmat[1,0] == 0 and cellmat[2,0] == 0 and cellmat[2,1] == 0:
        s += "    {0} {1} {2}\n".format(cellmat[0,0],cellmat[1,1],cellmat[2,2])
    else:
        assert cellmat[0,1] == 0 and cellmat[0,2] == 0 and cellmat[1,2] == 0
        s += "    {0} {1} {2} {3} {4} {5} {6} {7} {8}\n".format(cellmat[0,0],
                                                                cellmat[1,1],
                                                                cellmat[2,2],
                                                                cellmat[0,1],
                                                                cellmat[0,2],
                                                                cellmat[1,0],
                                                                cellmat[1,2],
                                                                cellmat[2,0],
                                                                cellmat[2,1],
                                                                )
    s += '#' + "\n#".join(lattice.doc) + "\n"
    print(s,end="")
    lattice.logger.info("Hook7: end.")


hooks = {7:hook7}
