"""THis is a simple script to initalise a DB
or to add devices and sensors into a DB
"""

import argparse as arg
import os

from src.in_io import sqlite as pysql
from src.in_io import in_io as inio


def parsing():
    """Argument Parser for coincidence analysis

    Returns
    -------
    parse
        The argument parser object
    """

    parse = arg.ArgumentParser(
        description=("Purpose: Creare a DB for logging inator data")
    )

    parse.add_argument(
        "-sql",
        metavar="SQL",
        type=str,
        help=("The SQL database path. Should be absolute"),
    )

    parse.add_argument(
        "-createdb",
        action="store_true",
        help=("If set will create a new DB if the given db doesn't exist"),
    )

    parse.add_argument(
        "-dev_file",
        metavar="DEVFILE",
        type=str,
        help=(
            "JSON file that contains the device information to be loaded into the SQL"
        ),
    )

    return parse


def set_up_inator_log(options: dict):
    """This function will set up an Inator logging database

    Parameters
    ----------
    options : dict
        the options to set up the database, identical to cli for the example script

    Returns
    -------
    bool
        whether the set up was successful or not
    """
    sql_db = options["sql"]
    setup_flag = False

    # load dev file
    if options["dev_file"]:
        dev_info = inio.read_device_info(options["dev_file"])

    if not os.path.exists(sql_db):
        print(f"❌ - The database {sql_db} does not exist")
        if not options["createdb"]:
            print(
                "❌ Please check if you want to create this DB or if it should already exist."
                "If you want it created rerun with the -createdb flag added"
            )
            exit()
        else:
            print("Will create the DB now")
            # Connect to existing sql database and get cursor
            dberror, con, cursor = pysql.connect_db(sql_db, 1)
    else:
        print(f"✅ The database {sql_db} exists. Will connect")
        dberror, con, cursor = pysql.connect_db(sql_db, 0)

    if dberror == 0:
        print(f"✅ Connected to {sql_db}")
        # Now create the devlist table
        # Check if it is present
        sql = pysql.check_table_exists(cursor, "devlist")
        if sql == []:
            print("devlist does not exist, creating")
            sql = pysql.create_dev_table(cursor)
        # Now need to get sensor information and fill the table
        if options["dev_file"]:
            print(f"Loading device info from {options["dev_file"]}")
            for device in dev_info["devices"]:
                sql = pysql.insert_dev_table(cursor, device)
                if sql == 1:
                    print("✅ Device info has been loaded")
                    # create the device tables

                    # need the device id
                    dev_id = cursor.lastrowid
                    print(
                        f"Creating tables for {device['device_name']},"
                        f" device id is {dev_id}"
                    )
                    table_name = f"{dev_id}_{device['device_name']}_details"
                    sql = pysql.check_table_exists(cursor, table_name)
                    if sql == []:
                        sql = pysql.create_dev_info_table(cursor, dev_id, device)
                        # now load the sensor information
                        sql = pysql.insert_dev_info_table(
                            cursor,
                            dev_id,
                            device,
                            device["sensors"],
                        )
                        print(f"✅ Created {table_name}")
                        # now create logging table
                        table_name = f"{dev_id}_{device['device_name']}"
                        print(f"Creating {table_name}")
                        sql = pysql.check_table_exists(cursor, table_name)
                        if sql == []:
                            sql = pysql.create_dev_log_table(cursor, dev_id, device)
                            setup_flag = True
                        else:
                            print(f"❌ {table_name} already exists?")
                            setup_flag = False
                    else:
                        print(f"❌ {table_name} already exists?")
                        setup_flag = False
        # while testing just close
        con.commit()
        cursor.close()
    else:
        print(f"❌ failed to connect to {sql_db}")

    return setup_flag


if __name__ == "__main__":
    print("Readying Logging DB")

    # get CLI arguments
    parsey = parsing()
    parsed_args, __ = parsey.parse_known_args()

    print(parsed_args)
    cli_options = {
        "sql": parsed_args.sql,
        "dev_file": parsed_args.dev_file,
        "createdb": parsed_args.createdb,
    }
    setupflag = set_up_inator_log(cli_options)
