"""Functions for input and output"""

import datetime
import json

import toml


def get_secrets(secret_path: str):
    """Open the toml file with the 'secrects' inside

    Parameters
    ----------
    secret_path : str
        path to the toml

    Returns
    -------
    _type_
        dictionary representing the toml file
    """
    with open(secret_path, "r", encoding="utf-8") as sec_in:
        try:
            sec = toml.load(sec_in)
        except FileNotFoundError:
            print(f"File {secret_path} not found")
            exit()

    auth = {}
    connect = {}
    topics = {}
    info = {}
    auth["name"] = sec["MQTT_USERNAME"]
    auth["pass"] = sec["MQTT_KEY"]
    connect["url"] = sec["MQTT_BROKER"]
    connect["port"] = sec["MQTT_PORT"]
    topics["topics"] = sec["MQTT_TOPIC"]
    info["inator"] = sec["INATOR_NAME"]
    auth["API_key"] = sec["FLASK_KEY"]
    topics["route"] = sec["FLASK_ROUTE"]

    return auth, connect, topics, info


def read_device_info(devfile: str):
    """Function to read in device info file for uploading to the db

    Parameters
    ----------
    devfile : str
        filepath

    Returns
    -------
    _type_
        json file in dictionary format
    """
    # add file checks here

    with open(devfile, "r", encoding="utf-8") as devin:
        devinfo = json.load(devin)

    return devinfo


def save_plain_text(filename: str, timestamp: datetime, data: dict):
    """Save data to a text file

    Parameters
    ----------
    filename : str
        the filename - as full path
    data : dict
        the data to save to file
    """
    # add file checks here

    with open(filename, "a", encoding="utf-8") as fileout:
        txt = timestamp.isoformat(timespec="seconds") + ","
        for value in data:
            txt = txt + f"{data[value]},"
        txt = txt[:-1] + "\n"
        fileout.writelines(txt)
