#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Coded by L1ghtM3n@protonmail.com

# Import modules
from os import path
from threading import Lock
from sqlite3 import connect
# Import packages
from core.paths import DATABASE_DIR


class DatabaseManager(object):
    """ Database manager """
    def __init__(self, db_file):
        # Check if path exists
        db_location = path.join(DATABASE_DIR, db_file)
        assert path.exists(db_location), f"Failed connect to database {db_file}"
        # Connect to database
        self.connection = connect(
            db_location,
            check_same_thread=False
        )
        # Create lock and cursor
        self.lock = Lock()
        self.cursor = self.connection.cursor()

    def execute(self, sql: str, values: list = [], commit_changes: bool = False) -> list:
        """ Execute sql commands """
        if commit_changes is True:
            self.lock.acquire(commit_changes)
            self.cursor.execute(sql, values)
            self.connection.commit()
            self.lock.release()
            return []
        else:
            self.cursor.execute(sql, values)
            return self.cursor.fetchall()
