package com.example.oscellamobile

import android.R
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.navigation.NavController
import com.example.oscellamobile.domain.utlis.Constant
import com.example.oscellamobile.models.Users
import io.github.jan.supabase.gotrue.auth
import io.github.jan.supabase.gotrue.providers.builtin.Email
import io.github.jan.supabase.postgrest.from
import kotlinx.coroutines.launch
import kotlinx.coroutines.selects.select


class Auth(): ViewModel() {
    fun onSignInEmailPassword(emailUser: String, passwordUser: String, navController: NavController) {
        viewModelScope.launch {
            try {
                val user = Constant.supabase.auth.signInWith(Email) {
                    email = emailUser
                    password = passwordUser
                }
                println(user.toString())
                println(Constant.supabase.auth.currentUserOrNull()!!.id)
                println("Success")
                navController.navigate("MainWindow/0")
            } catch (e: Exception) {
                println("Error")
                println(e.message.toString())
            }
        }
    }

    fun onSignUpEmail(emailUser: String, passwordUser: String, login: String, navController: NavController) {
        viewModelScope.launch {
            try{
                var  user =  Constant.supabase.auth.signUpWith(Email) {
                    email = emailUser
                    password = passwordUser
                }

                println(user.toString())
                println(Constant.supabase.auth.currentUserOrNull()!!.id)
                println("Success")
                val count = Constant.supabase.from("Users").select().data.count()
                val NewUser = Users(
                    id =  count.toInt(),
                    user = (Constant.supabase.auth.currentUserOrNull()!!.id).toString(),
                    login = login
                )
                Constant.supabase.from("Users").insert(NewUser)
                navController.navigate("Auth")
            }
            catch (e: Exception) {
                println("Error")
                println(e.message.toString())
            }

        }
    }
}
