# pylint:disable=missing-module-docstring,missing-class-docstring,missing-function-docstring
# pylint:disable=import-outside-toplevel
import os
import unittest
from unittest.mock import patch
import logging
import sqlite3

_TEST_LOGGER = "test_logger"
PROCESSED_FILES_DB = "test/processed_files.db"


@patch("soil.logger.PROCESSED_FILES_DB", new=PROCESSED_FILES_DB)
@patch("soil.logger._SOIL_LOGGER", new=_TEST_LOGGER)
class TestHashfileLogger(unittest.TestCase):
    @staticmethod
    def _init_storage():
        """Checks if the state files are writeable."""
        if not os.path.exists(PROCESSED_FILES_DB):
            os.mknod(PROCESSED_FILES_DB)
        with sqlite3.connect(PROCESSED_FILES_DB) as connection:
            connection.execute("DROP TABLE IF EXISTS processed_files")
            connection.execute(
                """
                CREATE TABLE processed_files (
                    file_name VARCHAR PRIMARY KEY,
                    date VARCHAR NOT NULL,
                    size int NOT NULL,
                    datatype VARCHAR NOT NULL,
                    state VARCHAR CHECK( state IN ('WAITING','PROCESSED','ERROR') ) NOT NULL
                )
                """
            )

    @staticmethod
    def _store_file_db(hexdigest, date, size, datatype):
        with sqlite3.connect(PROCESSED_FILES_DB) as connection:
            connection.execute(
                """
                INSERT INTO processed_files (file_name, date, size, datatype, state)
                VALUES (?,?,?,?,?)
                """,
                (hexdigest, date, size, datatype, "WAITING"),
            )

    def test_logs_handler(self):
        # importing inside method because of patch test_logger
        from soil.logger import logger

        TestHashfileLogger._init_storage()
        file = "hash_file_1"
        TestHashfileLogger._store_file_db(file, "2022-02-02", 1, "test1")
        logger.setLevel(logging.DEBUG)
        logger.debug(
            "%s has been processed successfully!",
            file,
            extra={"type": "processed", "file": file},
        )
        logger.debug(
            "%s has been processed successfully!",
            "file_not_existent",
            extra={"type": "processed", "file": "file_not_existent"},
        )
        with sqlite3.connect(PROCESSED_FILES_DB) as connection:
            results = connection.execute(
                """
                    SELECT *
                    FROM processed_files
                """
            ).fetchall()
        self.assertListEqual(
            [
                (
                    "hash_file_1",
                    "2022-02-02",
                    1,
                    "test1",
                    "WAITING",
                    "processed",
                    f"{file} has been processed successfully!",
                )
            ],
            results,
        )
