from supabase import create_client
from threading import Thread
import time


class ADB:

    def __init__(self, url, key):
        self.db = create_client(url, key)
        self.current_uid = None

    # ================= THREAD SİSTEM =================

    def _async(self, func, callback=None):
        def run():
            try:
                sonuc = func()
                if callback:
                    callback(sonuc)
            except Exception as e:
                print("ADB HATA:", e)

        Thread(target=run, daemon=True).start()

    # ================= AUTH =================

    def a_kayit_ol(self, email, sifre, callback=None):
        self._async(
            lambda: self.db.auth.sign_up({
                "email": email,
                "password": sifre
            }),
            callback
        )

    def a_giris_yap(self, email, sifre, callback=None):

        def islem():
            res = self.db.auth.sign_in_with_password({
                "email": email,
                "password": sifre
            })
            self.current_uid = res.user.id
            return self.current_uid

        self._async(islem, callback)

    def cikis_yap(self):
        try:
            self.db.auth.sign_out()
            self.current_uid = None
        except:
            pass

    # ================= VERİ TABANI =================

    def add(self, tablo, uid=None, callback=None, **veriler):

        def islem():
            if uid is None:
                uid_kullan = self.current_uid
            else:
                uid_kullan = uid

            if uid_kullan is None:
                raise Exception("UID yok, önce giriş yap")

            veriler["user_id"] = uid_kullan

            return self.db.table(tablo).insert(veriler).execute()

        self._async(islem, callback)

    def get(self, tablo, uid=None, callback=None):

        def islem():
            if uid is None:
                uid_kullan = self.current_uid
            else:
                uid_kullan = uid

            if uid_kullan is None:
                raise Exception("UID yok")

            return self.db.table(tablo)\
                .select("*")\
                .eq("user_id", uid_kullan)\
                .execute().data

        self._async(islem, callback)

    def update(self, tablo, uid=None, callback=None, **veriler):

        def islem():
            if uid is None:
                uid_kullan = self.current_uid
            else:
                uid_kullan = uid

            if uid_kullan is None:
                raise Exception("UID yok")

            return self.db.table(tablo)\
                .update(veriler)\
                .eq("user_id", uid_kullan)\
                .execute()

        self._async(islem, callback)

    def delete(self, tablo, uid=None, callback=None):

        def islem():
            if uid is None:
                uid_kullan = self.current_uid
            else:
                uid_kullan = uid

            if uid_kullan is None:
                raise Exception("UID yok")

            return self.db.table(tablo)\
                .delete()\
                .eq("user_id", uid_kullan)\
                .execute()

        self._async(islem, callback)


# ================= KULLANIMI DAHA BASİT OLSUN DİYE =================

_db = None


def baslat(url, key):
    global _db
    _db = ADB(url, key)


def a_kayit_ol(email, sifre, callback=None):
    _db.a_kayit_ol(email, sifre, callback)


def a_giris_yap(email, sifre, callback=None):
    _db.a_giris_yap(email, sifre, callback)


def add(tablo, uid=None, callback=None, **veriler):
    _db.add(tablo, uid, callback, **veriler)


def get(tablo, uid=None, callback=None):
    _db.get(tablo, uid, callback)


def update(tablo, uid=None, callback=None, **veriler):
    _db.update(tablo, uid, callback, **veriler)


def delete(tablo, uid=None, callback=None):
    _db.delete(tablo, uid, callback)