From ca370e60d3029dac83bbc8f88f8312587cf636df Mon Sep 17 00:00:00 2001
From: sqozz <sqozz@geekify.de>
Date: Wed, 13 Jul 2022 00:12:35 +0200
Subject: [PATCH] Add history abstraction

---
 history.py | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 51 insertions(+)
 create mode 100644 history.py

diff --git a/history.py b/history.py
new file mode 100644
index 0000000..b051d94
--- /dev/null
+++ b/history.py
@@ -0,0 +1,51 @@
+import sqlite3, time
+
+class History():
+    def __init__(self):
+        self.__db =  sqlite3.connect('history.sqlite')
+        self.__c = self.__db.cursor()
+        self.__c.execute("""
+                    CREATE TABLE IF NOT EXISTS numbers (
+                        id INTEGER PRIMARY KEY AUTOINCREMENT,
+                        number TEXT UNIQUE NOT NULL
+                    );
+        """)
+        self.__c.execute("""
+                    CREATE TABLE IF NOT EXISTS call_history (
+                        call_id INTEGER PRIMARY KEY AUTOINCREMENT,
+                        number_id INTEGER NOT NULL,
+                        direction INTEGER NOT NULL,
+                        time INTEGER NOT NULL,
+                        duration INTEGER,
+                        accepted INTEGER,
+                        FOREIGN KEY(number_id) REFERENCES numbers(id)
+                    );
+        """)
+        self.__db.commit()
+
+    def log_call(self, number, incoming):
+        call_time = int(time.time())
+        try:
+            self.__c.execute("INSERT INTO numbers(number) VALUES(?)", (number,))
+            number_id = self.__c.lastrowid
+        except sqlite3.IntegrityError:
+            number_id = self.__c.execute("SELECT id FROM numbers WHERE number=?", (number,)).fetchone()[0]
+
+        self.__c.execute("INSERT INTO call_history(direction, time, number_id) VALUES(?, ?, ?);", (int(incoming), call_time, number_id))
+        new_call_history_id = self.__c.lastrowid
+        self.__db.commit()
+        return new_call_history_id
+
+    def accept_call(self, call_id):
+        self.update_call_acception(call_id, True)
+
+    def decline_call(self, call_id):
+        self.update_call_acception(call_id, False)
+
+    def update_call_acception(self, call_id, accepted):
+        self.__c.execute("UPDATE call_history SET accepted=? WHERE call_id=?;", (accepted, call_id))
+        self.__db.commit()
+
+    def set_call_duration(self, call_id, duration):
+        self.__c.execute("UPDATE call_history SET duration=? WHERE call_id=?;", (duration, call_id))
+        self.__db.commit()