package com.example.doctor

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.ArrayAdapter
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import com.example.doctor.Auth.AuthActivity
import com.example.doctor.Auth.AuthFragment
import com.example.doctor.Auth.Model.AuthModel
import com.example.doctor.Pref.ConclusionPref
import com.example.doctor.Pref.SavePref
import com.example.doctor.Retrofit.DoctorApi
import com.example.doctor.Toast.showCustomInfoToast
import com.example.doctor.databinding.ActivityMainBinding
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import org.json.JSONObject
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

class MainActivity : AppCompatActivity() {
    private lateinit var binding: ActivityMainBinding
    private lateinit var doctorApi: DoctorApi

    //Токен
    private var Token = ""
    val prefDoctorSave = SavePref()
    val prefDoctorConclusion = ConclusionPref()
    var backPressedTime: Long = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        initRetrofit()

        MainAndAuth()


    }


    fun MainAndAuth() {
        Token = prefDoctorConclusion.conclusionToken(this)
        //CheckTokenAuth(Token)
        if (Token == "") {
            Auth()
        } else {
            CheckTokenAuth(Token)
        }
    }

    fun Auth() {
        supportFragmentManager.beginTransaction()
            .replace(R.id.CLMain, AuthFragment.newInstance())
            .commit()
    }

    fun Main() {
        fragment_inicializ()
    }

    @SuppressLint("SuspiciousIndentation")
    private fun CheckTokenAuth(token: String) {
        CoroutineScope(Dispatchers.IO).launch {
            val response = doctorApi.CheckToken("Bearer $token")
            runOnUiThread {
                val checkToken = response.body()
                val user1 = response.code()
                Log.i("12213213213", user1.toString())

                if (user1.toString() == "200") {
                    Main()
                } else {
                    Auth()
                }
            }

        }

    }


    //Инициализируем Retrofit
    private fun initRetrofit() {
        val interceptor = HttpLoggingInterceptor()
        interceptor.level = HttpLoggingInterceptor.Level.BODY

        val client = OkHttpClient
            .Builder()
            .addInterceptor(interceptor)
            .build()

        val retrofit = Retrofit.Builder()
            .baseUrl("http://mobileapp.vmeda.org/api/")
            .client(client)
            .addConverterFactory(GsonConverterFactory.create())
            .build()

        doctorApi = retrofit.create(DoctorApi::class.java)

    }

    private fun fragment_inicializ() {
        //Вывод фрагмента на активити при первоначальной загрузке
        supportFragmentManager.beginTransaction()
            .replace(R.id.CLMain, MainFragment.newInstance())
            .commit()//Заменяем наш экран на фрагмент (используем наш экран как основу)//R.id.placeHolder - куда всталяем //MainFragment.newInstance() - это то что мы вставляем

    }
//    override fun onBackPressed() {
//        if (backPressedTime + 3000 > System.currentTimeMillis()) {
//            super.onBackPressed()
//            finish()
//        } else {
//            AlertDialog.Builder(this@MainActivity)
//                .setTitle("Выйти")
//                .setMessage("Вы точно хотите выйти из приложения?")
//                .setPositiveButton("Да") { dialog, whichButton ->
//                    super.onBackPressed()
//                }
//                .setNegativeButton("Нет") { dialog, whichButton ->
//
//                }
//                .show()
//        }
//        backPressedTime = System.currentTimeMillis()
//    }

    override fun onResume() {
        super.onResume()

    }


}