import pathlib
import sqlite3
import uuid
import shutil


class DB:
    def __init__(self):
        self.path = pathlib.Path.home() / '.purple/chatty/db/chatty-history.db'

        self.con = sqlite3.connect(self.path, timeout=30)
        self.cur = self.con.cursor()


    def __enter__(self):
        return self


    def __exit__(self, exc_type, exc_val, exc_tb):
        self.con.close()

    
    def backup(self):
        bakpath = pathlib.Path('/tmp/chatty-history.db.bak')
        shutil.copy(self.path, bakpath)


    def get_thread_length(thread_id):
        self.cur.execute(
            'select count(*) from messages where thread_id = (?)',
                (thread_id,))
        return self.cur.fetchone()[0]


    def get_threads(self):
        self.cur.execute('''select
                  t.id,
                  coalesce(nullif(t.alias, ''), u.alias) as alias,
                  t.name
              from threads t
              left join users u on t.name = u.username
              left join (
                  select thread_id, max(time) as last_time
                  from messages
                  group by thread_id
            ) m on m.thread_id = t.id
            order by m.last_time desc''')
        return self.cur.fetchall()


    def insert_message(self, thread_id, msg):
        self.cur.execute('''insert into "messages" (
            uid, thread_id, sender_id, user_alias, body, body_type,
            direction, time, status, encrypted, preview_id, subject
            ) values (
              (?),
              (?),
              1, NULL, (?), 1, -1,
              strftime('%s', 'now'), 3, 0, NULL, NULL)''',
            (str(uuid.uuid4()), thread_id, msg)) 
        self.con.commit()


    def get_thread(self, thread_id):
        self.cur.execute(''' 
        with last_messages as (
            select messages.sender_id as sid, messages.time, messages.body
            from messages
            join threads on messages.thread_id = threads.id
            where threads.id = (?)
            order by messages.time desc
        )
        select sid, (select alias from users where id = sid), 
        datetime(time, 'unixepoch', 'localtime'), body
        from last_messages
        order by time asc''', (thread_id,))

        # [(sender_id, sender_alias, datetime, message), ...]
        return self.cur.fetchall()
