import configparser
import datetime
import logging
import tempfile
import zipfile
from dataclasses import dataclass
from pathlib import Path

from tqdm import tqdm


@dataclass
class Config:
    api_url: str
    log_dir: Path
    exe_path: Path
    auto_del: bool

    @staticmethod
    def get_config():
        conf_file = Path(__file__) / "../config.ini"
        conf_file = conf_file.resolve()

        config = configparser.ConfigParser()
        config.read(conf_file)

        logging.debug(dict(config["default"]))
        config = Config(**dict(config["default"]))
        config.log_dir = Path(config.log_dir)
        config.exe_path = Path(config.exe_path)
        return config


def get_list_of_files():
    # update the list of files when anything added to monitoring engine
    list_of_files = ["log.etl", "procmon.out", "etw.etl", "log.pcapng", "apimon.xml"]

    for j in ["before", "after"]:
        for i in ["tcp", "udp", "tcp6", "udp6"]:
            list_of_files += [f"network_{j}_{i}.csv"]
        for i in range(1, 6):
            list_of_files += [f"regshot_{j}{i}"]

    return list_of_files


def setup_monitoring_folder(log_dir, name=None):
    timestamp = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
    cur_monitoring_folder = log_dir / timestamp

    logging.info(f"Creating log_dir {cur_monitoring_folder}")
    cur_monitoring_folder.mkdir(parents=True)

    return cur_monitoring_folder, timestamp


def compress_files(list_of_files):
    logging.info("Compressing Files")
    tempf = tempfile.NamedTemporaryFile(delete=False, suffix=".zip")
    zipf = zipfile.ZipFile(tempf.name, "w", zipfile.ZIP_DEFLATED)

    ## For compressing all the files
    # for file in cur_monitoring_dir.rglob('*'):
    #    ziph.write(file)

    ## compressing using list_of_files
    for file in tqdm(list_of_files):
        if file.exists():
            zipf.write(file, arcname=file.parts[-1])
        else:
            logging.warning(f"{file} doesn't exist")

    zipf.close()
    return Path(tempf.name)
