import os
import sqlite3
import Shared
import json

class SettingsProvider():
	def __init__(Self):
		Self.Database = sqlite3.connect(os.path.join(Shared.DATAPATH, "settings.db"))
		Self.Cursor = Self.Database.cursor()
		#Self.Execute("DROP TABLE Destinations")
		#Self.Execute("DROP TABLE Shortcuts")
		Self.Execute("CREATE TABLE IF NOT EXISTS Settings (Key TEXT PRIMARY KEY, Value TEXT)")
		Self.Execute("CREATE TABLE IF NOT EXISTS Destinations (ID INTEGER PRIMARY KEY AUTOINCREMENT, Type TEXT, Name TEXT, Data TEXT)")
		Self.Execute("CREATE TABLE IF NOT EXISTS Shortcuts (ID INTEGER PRIMARY KEY AUTOINCREMENT, Keys TEXT, Action TEXT, Destination INT)")

	def Dispose(Self):
		Self.Database.close()

	def Execute(Self, Query, Arguments = ()):
		Self.Cursor.execute(Query, Arguments)
		Self.Database.commit()

		return Self.Cursor.fetchall()

	def Set(Self, Key, Value):
		Self.Execute("INSERT OR REPLACE INTO Settings (Key, Value) VALUES (?, ?)", (Key, Value))

	def Get(Self, Key):
		return Self.Execute("SELECT * FROM Settings WHERE Key = ?", (Key,))[0][1]

	def AddShortcut(Self, Keys, Action, Destination):
		Self.Execute("INSERT INTO Shortcuts (Keys, Action, Destination) VALUES (?, ?, ?)", (Keys, Action, Destination))

	def RemoveShortcut(Self, ID):
		Self.Execute("DELETE FROM Shortcuts WHERE ID = ?", (ID,))

	def GetShortcutByID(Self, ID):
		List = Self.GetShortcutList()

		for Shortcut in List:
			if (Shortcut.ID == ID):
				return Shortcut

	def GetShortcutList(Self):
		Data = Self.Execute("SELECT * FROM Shortcuts")
		List = []

		for ShortcutData in Data:
			List.append(Shortcut(ShortcutData[0], ShortcutData[1], ShortcutData[2], ShortcutData[3]))

		return List

	def AddDestination(Self, Type, Name, Data):
		Self.Execute("INSERT INTO Destinations (Type, Name, Data) VALUES (?, ?, ?)", (Type, Name, json.dumps(Data)))

	def RemoveDestination(Self, ID):
		Self.Execute("DELETE FROM Destinations WHERE ID = ?", (ID,))
		Self.Execute("DELETE FROM Shortcuts WHERE Destination = ?", (ID,))

	def GetDestinationByID(Self, ID):
		List = Self.GetDestinationList()

		for Destination in List:
			if (Destination.ID == ID):
				return Destination

	def GetDestinationList(Self):
		Data = Self.Execute("SELECT * FROM Destinations")
		List = []

		for DestData in Data:
			List.append(Destination(DestData[0], DestData[1], DestData[2], DestData[3]))

		return List


class Destination():
	def __init__(Self, ID, Type, Name, Data):
		Self.ID = ID
		Self.Type = Type
		Self.Name = Name
		Self.Data = json.loads(Data)

class Shortcut():
	def __init__(Self, ID, Keys, Action, Destination):
		Self.ID = ID
		Self.Keys = Keys
		Self.Action = Action
		Self.Destination = Destination