package com.mob5.smarthousew

import android.app.Activity
import android.content.Context
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Patterns
import android.view.View
import android.widget.Button
import android.widget.EditText
import androidx.appcompat.app.AlertDialog
import com.mob5.smarthouse.common.Login
import com.mob5.smarthouse.common.MyRetrofit
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class SignInScreen : Activity() {
    lateinit var email: EditText
    lateinit var pass: EditText
    lateinit var signinbtn: Button

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_sign_in_screen)

        email = findViewById(R.id.signin_email)
        pass = findViewById(R.id.signin_pass)
        signinbtn = findViewById(R.id.signin_btn)

        signinbtn.setOnClickListener{
            if (email.text.isNotEmpty() && pass.text.isNotEmpty()){
                if (Patterns.EMAIL_ADDRESS.matcher(email.text).matches()){
                    val call = MyRetrofit.getRetrofit().login(email.text.toString(), pass.text.toString(), "5FA1B987-3890-4A87-9712-ACDEAD0173AE")
                    call.enqueue(object : Callback<Login> {
                        override fun onResponse(call: Call<Login>, response: Response<Login>) {
                            if (response.body()?.token != null){
                                getSharedPreferences("data", Context.MODE_PRIVATE).edit().putString("token", response.body()?.token).apply()
                                startActivity(Intent(this@SignInScreen, MainScreen::class.java))
                            }
                            else AlertDialog.Builder(this@SignInScreen).setTitle("Ошибка").setMessage("Неверный логин или пароль").setPositiveButton("OK", null).show()
                        }

                        override fun onFailure(call: Call<Login>, t: Throwable) {
                            AlertDialog.Builder(this@SignInScreen).setTitle("Ошибка").setMessage(t.message).setPositiveButton("OK", null).show()
                        }
                    })
                }
                else AlertDialog.Builder(this).setTitle("Ошибка").setMessage("Неверный email").setPositiveButton("OK", null).show()
            }
            else AlertDialog.Builder(this).setTitle("Ошибка").setMessage("Заполните все поля").setPositiveButton("OK", null).show()
        }
    }
}