package com.example.doctor.CodeError

import android.annotation.SuppressLint
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.CountDownTimer
import android.util.Log
import com.example.doctor.Auth.AuthActivity
import com.example.doctor.Enternet.EnternetActivity
import com.example.doctor.Enternet.EnternetCheck
import com.example.doctor.MainActivity
import com.example.doctor.Pref.ClearPref
import com.example.doctor.Pref.ConclusionPref
import com.example.doctor.Pref.SavePref
import com.example.doctor.R
import com.example.doctor.Retrofit.DoctorApi
import com.example.doctor.databinding.ActivityCode429Binding
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.Timer
import kotlin.concurrent.fixedRateTimer

class Code429Activity : AppCompatActivity() {
    private lateinit var binding:ActivityCode429Binding
    private lateinit var doctorApi: DoctorApi
    private lateinit var timer: Timer


    val prefDoctorConclusion = ConclusionPref()
    val prefDoctorClear = ClearPref()
    val prefDoctorSave = SavePref()

    //Класс проверки интеренета
    val enternetCheck = EnternetCheck()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityCode429Binding.inflate(layoutInflater)
        setContentView(binding.root)
    }

        fun CheckToken(){
            if (enternetCheck.isOnline(this@Code429Activity)) {
                initRetrofit()
                val Tokens = prefDoctorConclusion.conclusionToken(this@Code429Activity)
                CoroutineScope(Dispatchers.IO).launch {
                    val list = doctorApi.CheckToken("Bearer $Tokens")
                    runOnUiThread {


                        //Фиксируем полученные данные
                        val List = list.body()
                        val Nice = list.isSuccessful
                        val Code = list.code()
                        if(Code==500){
                            val intetn = Intent(this@Code429Activity, Code500Activity::class.java)
                            finish()
                            startActivity(intetn)
                        }
                        else if(Code==200) {
                            //Если нету ошибок
                            if (Nice) {
                                //Если нету ошибок
                                if (List != null) {

                                    Log.i("clogon1231111","clogon1231111")
                                    finish()
                                }

                            }
                        }
                        else if (Code == 401) {
                            val intetn = Intent(this@Code429Activity, AuthActivity::class.java)
                            finish()
                            startActivity(intetn)
                        }
                    }
                }
            } else {

                val intetn = Intent(this, EnternetActivity::class.java)
                finish()
                startActivity(intetn)
            }

        }

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

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

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

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

        }


        override fun onResume() {
            super.onResume()
            checkForUpdates(true)
        }

        override fun onStop() {
            super.onStop()
            timer.cancel()
            timer.purge()
        }

        private fun checkForUpdates(daemonIsTrue: Boolean) {

            timer = fixedRateTimer("default", daemonIsTrue, 0, 15000) {
                this@Code429Activity.runOnUiThread {
                    CheckToken()
                }
            }

        }


}