from pathlib import Path
from random import randint
import click

from hpcflow.sdk.core.utils import get_process_stamp


def get_demo_software_CLI(app):
    """Generate the CLI to provide an example software."""

    @click.group()
    def demo_software():
        click.echo("demo software!")

    @demo_software.command("doSomething")
    @click.option("--infile1", "-i1", type=click.Path(exists=True), required=True)
    @click.option("--infile2", "-i2", type=click.Path(exists=True), required=True)
    @click.option("--value", "-v")
    @click.option("--out", "-o")
    def demo_do_something(infile1, infile2, value=None, out=None):

        click.echo("trying to do something")

        with Path(infile1).open("r") as handle:
            file_id_1 = int(handle.readline().strip())
        with Path(infile2).open("r") as handle:
            file_id_2 = int(handle.readline().strip())

        if out is None:
            out = "outfile.txt"
        out_path = Path(out)
        with out_path.open("a") as handle:
            handle.write("{}\n".format(randint(0, 1e6)))
            handle.write(
                "{} Generated by `doSomething --infile1 {} --infile2 {}`.\n".format(
                    get_process_stamp(), infile1, infile2
                )
            )
            if value:
                handle.write("{} Value: {}\n".format(get_process_stamp(), value))
            handle.write(
                "{} Original file ID: {}: {}\n".format(
                    get_process_stamp(), infile1, file_id_1
                )
            )
            handle.write(
                "{} Original file ID: {}: {}\n".format(
                    get_process_stamp(), infile2, file_id_2
                )
            )

    return demo_software
