import argparse
import configparser
import shutil
import sys
import traceback

from pathlib import Path

from lambend.__version__ import __version__
from lambend.expiry_wrapper import check_expiry
from lambend.lambendIO import LambendIO

def main():
    """Entry point of the command line application - lambend."""
    # check_expiry()

    parser = argparse.ArgumentParser(description='lambend : Analysis \
    of Anisotropic laminates Under Transverse Loads.')
    parser.add_argument("config", type=str, nargs='?', default=None, help="specify configuration file")
    parser.add_argument("-v", "--version", help="show version number", action='version', version='3pc-lambend ' + __version__)
    parser.add_argument("-s", "--sample", help="copy example files in the current directory", action="store_true")
    args = parser.parse_args()

    if args.sample:
        print('Copying sample file in current folder...')
        examples = Path(__file__).parent / 'examples'
        destination = Path(".") / 'examples'
        shutil.copytree(examples, destination, dirs_exist_ok=True)
        sys.exit()

    if args.config is None:
        sys.exit("No config file to run analysis. Try lambend -h")
    
    config = configparser.ConfigParser()
    config.read(args.config)

    materialFile = config["files"]["materials"]
    plyFile = config["files"]["plies"]
    laminateFile = config["files"]["laminates"]
    panelFile = config["files"]["panels"]
    loadsFile = config["files"]["loads"]
    outputFile = config["files"]["output"]
    number_of_terms = int(config["analysis"]["number_of_terms"])
    number_of_points_x = int(config["analysis"]["number_of_points_x"])
    number_of_points_y = int(config["analysis"]["number_of_points_y"])
    output_K = config["analysis"]["output_K"]
    output_K = output_K.lower()
    output_P = config["analysis"]["output_P"]
    output_P = output_P.lower()

    lmbIO = LambendIO(materialFile=materialFile, plyFile=plyFile,
    laminateFile=laminateFile, panelFile=panelFile, loadsFile=loadsFile,
    outputFile=outputFile, number_of_terms=number_of_terms,
    number_of_points_x=number_of_points_x, number_of_points_y=number_of_points_y,
    output_K=output_K, output_P=output_P)
    try:
        lmbIO._writeResults()
    except Exception:
        with open(outputFile, 'w') as fh:
            traceback.print_exc(limit=None, file=fh, chain=True)
