#!python
"""
Geometry handler for different formats
"""
from __future__ import print_function, division

import sys, os.path as osp
import argparse as arg

import sisl


def run():

    # The file *MUST* be the first argument
    # (except --help|-h)

    # We cannot create a separate ArgumentParser to retrieve a positional arguments
    # as that will grab the first argument for an option!

    # Start creating the command-line utilities that are the actual ones.
    description = """
This manipulation utility is highly advanced and one should note that the ORDER of
options is determining the final structure. For instance:

   {0} geom.xyz --repeat x 2 --repeat y 2

is NOT equivalent to:

   {0} geom.xyz --repeat y 2 --repeat x 2

This may be unexpected but enables one to do advanced manipulations.

Additionally, in between arguments, one may store the current state of the geometry
by writing to a standard file.

   {0} geom.xyz --repeat y 2 geom_repy.xyz --repeat x 2 geom_repy_repx.xyz

will create two files:
   geom_repy.xyz
will only be repeated 2 times along the second lattice vector, while:
   geom_repy_repx.xyz
will be repeated 2 times along the second lattice vector, and then the first
lattice vector.
    """.format(osp.basename(sys.argv[0]))

    if len(sys.argv) == 1:
        # no arguments
        # fake a help
        argv = ['--help']
    else:
        argv = sys.argv[1:]

    
    if len(argv) >= 1:
        # Get the file
        geom_file = argv[0]
        try:
            geom_sile = sisl.get_sile(geom_file)
            is_file = True
        except:
            geom_sile = geom_file
            is_file = osp.isfile(geom_file)

        if is_file:
            geom = sisl.Geometry.read(geom_sile)
            argv.pop(0)
        elif ('-h' in argv) or ('--help' in argv):
            # Fake help...
            geom = sisl.Geometry([0,0,0])
        else:
            # The file that the user request, does not exist
            raise ValueError("File: '"+geom_file+"' cannot be found. Please supply a readable file!")

    p = arg.ArgumentParser('Manipulates geometries in commonly encounterd files.',
                           formatter_class=arg.RawDescriptionHelpFormatter,
                           description=description)

    # We are good to go!!!

    # Append the geometry arguments from the object
    p, namespace = geom.ArgumentParser(p, **sisl.Geometry._ArgumentParser_args_single())
    setattr(namespace, '_input_file', geom_file)

    args = p.parse_args(argv, namespace=namespace)
    g = args._geometry

    if not args._stored_geometry:
        # We should write out the information to the stdout
        # This is merely for testing purposes and may not be used for anything.
        print('Cell:')
        for i in range(3):
            print('  {0:10.6f} {1:10.6f} {2:10.6f}'.format(*g.cell[i,:]))
        print('SuperCell:')
        print('  {0:d} {1:d} {2:d}'.format(*g.nsc))
        print(' {:>10s} {:>10s} {:>10s}  {:>3s}'.format('x','y','z','Z'))
        for ia in g:
            print(' {1:10.6f} {2:10.6f} {3:10.6f}  {0:3d}'.format(g.atom[ia].Z,
                                                                  *g.xyz[ia,:]))


if __name__ == "__main__":
    run()
