# ble_storage.py
#
# Copyright 2024 Christopher Talbot
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.
#
# SPDX-License-Identifier: GPL-3.0-or-later

from gi.repository import Adw
from gi.repository import Gtk
import gettext
import json
import time
import os
import hashlib
import sqlite3
from datetime import datetime, timezone

import gtk_meshtastic_client.utils as utils
import gtk_meshtastic_client.connection_page as connection_page
import gtk_meshtastic_client.bluetooth_device_row as bluetooth_device_row

class BLEStorage():

    database_name = 'invalid'
    version = 0

    def retrieve_ble_devices(self, connection_page_bin):
        con = sqlite3.connect(self.database_name)
        cur = con.cursor()
        res = cur.execute("SELECT * FROM favorite_ble_devices")
        rows = res.fetchall()
        for row in rows:
            connection_page_bin.bluetooth_devices_group.set_visible(True)
            new_device = bluetooth_device_row.BluetoothDeviceRow()

            new_device.set_device_name(row[0])
            new_device.set_device_address(row[1])
            new_device.set_connection_page(connection_page_bin)
            new_device.set_ble_database(connection_page_bin.ble_database)
            new_device.toggle_favorite_node(False)

            connection_page_bin.bluetooth_devices_list_box.append(new_device)
            connection_page_bin.bluetooth_devices_list_box_children += 1

        con.commit()
        cur.close()
        con.close()

    def remove_node_from_database(self, address):
        con = sqlite3.connect(self.database_name)
        cur = con.cursor()

        cur.execute("DELETE FROM favorite_ble_devices WHERE address = ? ", (address, ))
        con.commit()
        cur.close()
        con.close()

    def add_node_to_database(self, name, address):
        con = sqlite3.connect(self.database_name)
        cur = con.cursor()
        ble_device_attribute = []

        ble_device_attribute.append(name)

        ble_device_attribute.append(address)

        #favorite_ble_devices(name, address)
        cur.execute("INSERT INTO favorite_ble_devices VALUES(?, ?)", ble_device_attribute)
        con.commit()
        cur.close()
        con.close()

    def __init__(self):
        app = Gtk.Application.get_default()

        self.logger = app.logger

        self.database_name = utils.meshtastic_config_dir + '/ble_devices_v' + str(self.version) + '.db'

        #if the database doesn't exist, create new table
        if not os.path.exists(self.database_name):
            self.logger.debug("Creating new database")
            con = sqlite3.connect(self.database_name)
            cur = con.cursor()
            cur.execute("CREATE TABLE favorite_ble_devices(name, address)")
            con.commit()
            cur.close()
            con.close()
