""" Database writer. Obsolete code that was moved into the process and was
    pushed out to this file """
import logging
import signal
import sqlite3
import time
from multiprocessing import Process, Value

from utils.ether_service.utils.log import init_logging

logger = logging.getLogger(__name__)


class DatabaseWriter(Process):
    """ Database Writer thread """

    def __init__(self, db_name, db_edit_queue, db_return_queue,
                 loglevel=logging.INFO):
        self.database_name = db_name
        self.db_edit_queue = db_edit_queue
        self.db_return_queue = db_return_queue
        self._is_running = Value('i', 0)
        self._started = Value('i', 0)
        self.loglevel = loglevel
        super().__init__(name=self.__class__.__name__, daemon=True)

    @property
    def has_started(self) -> bool:
        """ return _server """
        with self._started.get_lock():
            return self._started.value == 1

    @has_started.setter
    def has_started(self, value: bool) -> None:
        """ set _started """
        with self._started.get_lock():
            self._started.value = 1 if value else 0

    @property
    def is_running(self):
        """ Get _is_running safely """
        with self._is_running.get_lock():
            return self._is_running.value == 1

    @is_running.setter
    def is_running(self, value: bool):
        """ set _is_running safely """
        with self._is_running.get_lock():
            self._is_running.value = 1 if value else 0

    def start(self):
        """ Start the process """
        logger.warning("start")
        self.is_running = True
        super().start()

    def stop(self):
        """ Stop the process """
        self.db_edit_queue.put(("close", None, True))
        self.db_return_queue.get(timeout=1)
        self.is_running = False

    # noinspection SqlDialectInspection
    def run(self):
        """ One thread responsible for all database write operations. """

        init_logging(level=self.loglevel)
        signal.signal(signal.SIGINT, lambda x, y: None)
        signal.signal(signal.SIGTERM, lambda x, y: None)

        conn = sqlite3.connect(self.database_name)
        c = conn.cursor()
        c.execute("""CREATE TABLE IF NOT EXISTS receivers (
            station_id TEXT UNIQUE,
            isAuto INTEGER,
            isMobile INTEGER,
            isSingle INTEGER,
            latitude REAL,
            longitude REAL)
        """)
        c.execute("""CREATE TABLE IF NOT EXISTS interest_areas (
            uid INTEGER,
            aoi_type TEXT,
            latitude REAL,
            longitude REAL,
            radius INTEGER)
        """)
        c.execute("""CREATE TABLE IF NOT EXISTS intersects (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            time INTEGER,
            latitude REAL,
            longitude REAL,
            num_parents INTEGER,
            confidence INTEGER,
            aoi_id INTEGER)""")
        c.execute("""CREATE TABLE IF NOT EXISTS lobs (time INTEGER,
            station_id TEXT,
            latitude REAL,
            longitude REAL,
            confidence INTEGER,
            lob REAL)""")
        conn.commit()

        self.has_started = True

        while self.is_running:
            command, items, reply = self.db_edit_queue.get()
            if command == "done":
                conn.commit()
            elif command == "close":
                conn.commit()
                conn.close()
                if reply:
                    self.db_return_queue.put(True)
                break
            else:
                c.executemany(command, items)
                if reply:
                    self.db_return_queue.put(True)
            time.sleep(0.001)
