#!/usr/bin/env python

import argparse
import os
from configparser import ConfigParser, ExtendedInterpolation
import pathlib
import socket
import glob
import shutil

from htmlcreator import HTMLDocument
from scrinet.workflow.pipe_utils import init_logger


def find_files(dirname, pattern):
    p = pathlib.Path(dirname)
    return list(p.glob(f"**/{pattern}"))

def get_user():
    return os.environ["USER"]

def get_hostname():
    return socket.getfqdn()

def guess_url(web_dir, host, user):
    """Taken from PESummary (https://git.ligo.org/lscsoft/pesummary)

    Guess the base url from the host name

    Parameters
    ----------
    web_dir: str
        path to the web directory where you want the data to be saved
    host: str
        the host name of the machine where the python interpreter is currently
        executing
    user: str
        the user that is current executing the python interpreter
    """
    ligo_data_grid = False
    if 'public_html' in web_dir:
        ligo_data_grid = True
    if ligo_data_grid:
        path = web_dir.split("public_html")[1]
        if "raven" in host or "arcca" in host:
            url = "https://geo2.arcca.cf.ac.uk/~{}".format(user)
        elif 'ligo-wa' in host:
            url = "https://ldas-jobs.ligo-wa.caltech.edu/~{}".format(user)
        elif 'ligo-la' in host:
            url = "https://ldas-jobs.ligo-la.caltech.edu/~{}".format(user)
        elif "cit" in host or "caltech" in host:
            url = "https://ldas-jobs.ligo.caltech.edu/~{}".format(user)
        elif 'uwm' in host or 'nemo' in host:
            url = "https://ldas-jobs.phys.uwm.edu/~{}".format(user)
        elif 'phy.syr.edu' in host:
            url = "https://sugar-jobs.phy.syr.edu/~{}".format(user)
        elif 'vulcan' in host:
            url = "https://galahad.aei.mpg.de/~{}".format(user)
        elif 'atlas' in host:
            url = "https://atlas1.atlas.aei.uni-hannover.de/~{}".format(user)
        elif 'iucca' in host:
            url = "https://ldas-jobs.gw.iucaa.in/~{}".format(user)
        elif 'hawk' in host:
            url = "https://ligo.gravity.cf.ac.uk/~{}".format(user)
        else:
            url = "https://{}/~{}".format(host, user)
        url += path
    else:
        url = "https://{}".format(web_dir)
    return url

if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        formatter_class=argparse.ArgumentDefaultsHelpFormatter,
        description="""Condor dag generator. If 'exe' options are parsed then
        all exe's will be generated. If a subset are parsed then only those
        will be generated.
        """
        )

    parser.add_argument("--output-dir", type=str, required=True,
                        help="path to output directory. Where the html page will be.")

    parser.add_argument("--results-dir", type=str, required=True,
                        help="path to results directory.")
    # parser.add_argument("--plot-dag", help="make a plot of the dags",
    #                     action="store_true")

    args = parser.parse_args()

    logger = init_logger()


    logger.info(f"current file: {__file__} ")


    logger.info(f"Making output-dir: {args.output_dir}")
    os.makedirs(f"{args.output_dir}", exist_ok=True)

    logger.info("looking for config file with pattern 'config*.ini'")
    glob_result = glob.glob(os.path.join(args.results_dir, "config*.ini"))
    logger.info(f"result of glob: {glob_result}")
    logger.info("taking first result from glob")
    config_file = glob_result[0]

    logger.info(f"copying config file to output dir: {args.output_dir}")
    shutil.copyfile(config_file, os.path.join(args.output_dir, config_file.split('/')[-1]))

    logger.info(f"reading config file: {config_file}")
    config = ConfigParser(interpolation=ExtendedInterpolation())
    config.optionxform = str
    config.read(config_file)

    name = config.get("workflow", "name")
    accounting_group = config.get("workflow", "accounting_group")
    root_data_output_dir = config.get("workflow", "root-data-output-dir")

    path1 = pathlib.Path(root_data_output_dir)
    path2 = pathlib.Path(args.results_dir)
    if path1.resolve() != path2.resolve():
        logger.warn("root_data_output_dir from config is not the same as the input results_dir")
        logger.warn(f"root_data_output_dir: {root_data_output_dir}")
        logger.warn(f"results_dir: {args.results_dir}")

    log_dir = config.get("workflow", "log_dir")
    data1 = config.get("workflow", "data1")
    data2 = config.get("workflow", "data2")
    try:
        basis_method = config.get("ts", "basis-method")
    except:
        basis_method = None

    # Create new document with default CSS style
    document = HTMLDocument()

    # Set document title
    document.set_title(f'{name}')

    # Add main header
    document.add_header('scrinet results page', level='h1', align='center')

    # Add section header
    document.add_header('Intro')  # defaults: level='h2' align='left'

    document.add_text(f'name: {name}')  # defaults: size='16px', indent='0' alight='left'
    document.add_text(f'root-data-output-dir: {root_data_output_dir}')
    document.add_text(f'log_dir: {log_dir}')
    document.add_text(f'data1: {data1}')
    document.add_text(f'data2: {data2}')
    document.add_text(f'basis method: {basis_method}')
    document.add_text(f'accounting_group: {accounting_group}')

    # Embed images
    document.add_header('images section')

    files = find_files(dirname=root_data_output_dir, pattern="*.png")

    logger.info("adding plots")
    for fil in files:
        # skip plotting all training and validation points
        if 'fits/plots' in str(fil):
            continue
        document.add_header(f'{fil}', level='h3')
        document.add_image(image=fil, title=f'{fil}', height=256)

    # Write to file
    output_filepath = os.path.join(args.output_dir, 'results.html')
    document.write(output_filepath)
    logger.info(f"result page: {output_filepath}")

    logger.info("guessing URL")
    user = get_user()
    host = get_hostname()
    url = guess_url(web_dir=output_filepath, host=host, user=user)
    logger.info(f"user: {user}")
    logger.info(f"host: {host}")
    logger.info(f"url: {url}")
