#!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} ElectrostaticPotential.grid.nc --diff Other.grid.nc --sub z 0.:0.2f

is NOT equivalent to:

   {0} ElectrostaticPotential.grid.nc --sub z 0.:0.2f --diff Other.grid.nc

This may be unexpected but enables one to do advanced manipulations.
    """.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
        grid_file = argv[0]
        try:
            grid_sile = sisl.get_sile(grid_file)
            is_file = True
        except:
            grid_sile = grid_file
            is_file = osp.isfile(grid_file)

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

    p = arg.ArgumentParser('Manipulates real-space grids in commonly encounterd files.',
                           formatter_class=arg.RawDescriptionHelpFormatter,
                           description=description)

    # We are good to go!!!

    # Append the geometry arguments from the object
    p, namespace = grid.ArgumentParser(p, **sisl.Grid._ArgumentParser_args_single())

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

    if not args._stored_grid:
        # We should write out the information to the stdout
        # This is merely for testing purposes and may not be used for anything.
        print(g)


if __name__ == "__main__":
    run()
