#!/usr/bin/env python
from dfttools.simple import parse
from dfttools.types import Cell
from dfttools.formatters import xsf_structure

import argparse
import inspect
import os
import tempfile


def run_xcrysden(*c):
    """
    Runs xcrysden.
    Args:
        *c: atomic structures to show;
    """
    with tempfile.NamedTemporaryFile('w+') as f:
        f.write(xsf_structure(*c))
        f.flush()
        f.seek(0)
        os.system('xcrysden --xsf "{name}"'.format(name=f.name))


def xcrysden(source, verbose=0):
    """
    Parse and open a structure in xcrysden.

    Args:
        source (Cell, file, str): structure or the file containing the structure to display;
        verbose (bool): verbose output;
    """
    def v(text):
        if verbose:
            print(text)

    if isinstance(source, Cell):
        pass

    elif isinstance(source, str):
        v("Parsing {} ...".format(source))
        with open(source, 'r') as f:
            cell = parse(f, "unit-cell")

    else:
        cell = parse(source, "unit-cell")

    v("Opening ...")
    if isinstance(cell, Cell):
        run_xcrysden(cell)
    else:
        run_xcrysden(*cell)


if __name__ == "__main__":
    spec = inspect.getfullargspec(xcrysden)
    defaults = dict(zip(spec.args[-len(spec.defaults):], spec.defaults))

    parser = argparse.ArgumentParser(description="Parse and display atomic structures using xcrysden")
    parser.add_argument("source", help="file containing the structure", metavar="FILENAME", type=str)
    parser.add_argument("-v", "--verbose", action="store_true", help="verbose output")
    options = parser.parse_args()

    xcrysden(options.source, verbose=options.verbose)
