package com.example.doctor.Patients

import android.content.Context
import android.content.Intent
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.activity.viewModels
import androidx.core.content.ContentProviderCompat.requireContext
import com.example.doctor.Auth.AuthActivity
import com.example.doctor.CodeError.Code429Activity
import com.example.doctor.CodeError.Code500Activity
import com.example.doctor.DoctorViewModel
import com.example.doctor.Enternet.EnternetActivity
import com.example.doctor.Enternet.EnternetCheck
import com.example.doctor.Patients.Reports.PatientFragment
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.ActivityPatientBinding
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 PatientActivity : AppCompatActivity() {
    private lateinit var binding: ActivityPatientBinding
    private lateinit var doctorApi: DoctorApi
    private lateinit var timer: Timer


    val prefDoctorConclusion = ConclusionPref()
    val prefDoctorClear = ClearPref()
    val prefDoctorSave = SavePref()
    private val modelDoctor: DoctorViewModel by viewModels()//Инициализировали класс
    var idPatient = 0

    //Класс проверки интеренета
    val enternetCheck = EnternetCheck()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityPatientBinding.inflate(layoutInflater)
        setContentView(binding.root)
        supportFragmentManager.beginTransaction().replace(R.id.CLPatientActivity, PatientFragment.newInstance()).commit()//Заменяем наш экран на фрагмент (используем наш экран как основу)//R.id.placeHolder - куда всталяем //MainFragment.newInstance() - это то что мы вставляем
        idPatient = prefDoctorConclusion.conclusionIdPatient(this)


    }


    //Получения списка анкет ДО и ПОСЛЕ для пациента
    fun QBAPatientList(id:Int){
        if (enternetCheck.isOnline(this@PatientActivity)) {
            initRetrofit()
            val Tokens = prefDoctorConclusion.conclusionToken(this@PatientActivity)
            CoroutineScope(Dispatchers.IO).launch {
                val list = doctorApi.GetPatientBAQiestionar("Bearer $Tokens",id)
                runOnUiThread {

                    //Фиксируем полученные данные
                    val List = list.body()
                    val Nice = list.isSuccessful
                    val Code = list.code()
                    if(Code==429){
                        val intetn = Intent(this@PatientActivity, Code429Activity::class.java)

                        startActivity(intetn)
                    }
                    else if(Code==200) {
                        //Если нету ошибок
                        if (Nice) {
                            if (List != null) {
                                if(List?.questionnaire !=null){
                                    modelDoctor.qbaList.value = List.questionnaire
                                }
                            }
                        }

                        //2
                        GetPatientID(idPatient)

                    }
                    else if (Code == 500) {
                        val intetn = Intent(this@PatientActivity, Code500Activity::class.java)

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

                }

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

    }

    private fun GetPatientID(idPatient: Int) {
        if (enternetCheck.isOnline(this)) {
            initRetrofit()
            val Tokens = prefDoctorConclusion.conclusionToken(this)
            CoroutineScope(Dispatchers.IO).launch {
                val listPatient = doctorApi.GetPatientID("Bearer $Tokens", idPatient)
                runOnUiThread {

                    //Фиксируем полученные данные
                    val List = listPatient.body()
                    val Nice = listPatient.isSuccessful
                    val Code = listPatient.code()
                    if(Code==429){
                        val intetn = Intent(this@PatientActivity, Code429Activity::class.java)

                        startActivity(intetn)
                    }
                    else if(Code==200) {
                        //Если нету ошибок
                        if (Nice) {
                            if (List != null) {
                                modelDoctor.patientCurrent.value = List

                            }
                        }

                        //3
                        GetCoursesAllSport(idPatient)

                    }
                    else if (Code == 500) {
                        val intetn = Intent(this@PatientActivity,Code500Activity::class.java)

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

            }
        } else {
            val intetn = Intent(this, EnternetActivity::class.java)

            finish()
            startActivity(intetn)
        }

    }

    //Вывод всех курсов
    fun GetCoursesAllSport(idPatient: Int){
        if (enternetCheck.isOnline(this)) {
            initRetrofit()
            val Tokens = prefDoctorConclusion.conclusionToken(this)
            CoroutineScope(Dispatchers.IO).launch {
                val listProduct = doctorApi.GetCoursAllPatient("Bearer $Tokens",idPatient)
                runOnUiThread {


                    //Фиксируем полученные данные
                    val List = listProduct.body()
                    val Nice = listProduct.isSuccessful
                    val Code = listProduct.code()
                    if(Code==429){
                        val intetn = Intent(this@PatientActivity, Code429Activity::class.java)

                        startActivity(intetn)
                    }
                    else if(Code==200) {
                        //Если нету ошибок
                        if (Nice) {
                            if (List != null) {
                                modelDoctor.SportCoursList.value = List.courses

                            }
                        }

                        //4
                        GetCoursesYouSport(idPatient)

                    }
                    else if (Code == 500) {
                        val intetn = Intent(this@PatientActivity, Code500Activity::class.java)

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

            finish()
            startActivity(intetn)
        }

    }


    //Получения списка курсов созданных доктором
    fun GetCoursesYouSport(idPatient:Int) {
        if (enternetCheck.isOnline(this)) {
            initRetrofit()
            val Tokens = prefDoctorConclusion.conclusionToken(this)
            CoroutineScope(Dispatchers.IO).launch {
                val listCoursesDoctor = doctorApi.GetCoursesDoctorPatient("Bearer $Tokens",idPatient)

                runOnUiThread {


                    //Фиксируем полученные данные
                    val List = listCoursesDoctor.body()
                    val Nice = listCoursesDoctor.isSuccessful
                    val Code = listCoursesDoctor.code()
                    if(Code==429){
                        val intetn = Intent(this@PatientActivity, Code429Activity::class.java)

                        startActivity(intetn)
                    }
                    else if(Code==200) {
                        //Если нету ошибок
                        if (Nice) {
                            if (List != null) {
                                modelDoctor.SportCoursDoctorList.value = List.courses_doctor

                            }
                        }

                        //5
                        GetCoursesSportYes(idPatient)

                    }
                    else if (Code == 500) {
                        val intetn = Intent(this@PatientActivity, Code500Activity::class.java)

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

                }

            }
        } else {
            val intetn = Intent(this, EnternetActivity::class.java)

            finish()
            startActivity(intetn)
        }

    }

    //Получения списка пациентов
    fun GetCoursesSportYes(id_patient:Int) {
        if (enternetCheck.isOnline(this)) {
            initRetrofit()
            val Tokens = prefDoctorConclusion.conclusionToken(this)
            CoroutineScope(Dispatchers.IO).launch {
                val sportEdit = doctorApi.GetCoursesSportYes("Bearer $Tokens", id_patient)
                runOnUiThread {


                    //Фиксируем полученные данные
                    val List = sportEdit.body()
                    val Nice = sportEdit.isSuccessful
                    val Code = sportEdit.code()
                    if(Code==429){
                        val intetn = Intent(this@PatientActivity, Code429Activity::class.java)

                        startActivity(intetn)
                    }
                    else if(Code==200) {
                        //Если нету ошибок
                        if (Nice) {
                            if (List != null) {
                                modelDoctor.EditSportListYes.value = List.set_of_sports_exercises_yes

                            }
                        }
                        //6
                        GetCoursesSportNo(idPatient)
                    }
                    else if (Code == 500) {
                        val intetn = Intent(this@PatientActivity, Code500Activity::class.java)

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

            }
        } else {
            val intetn = Intent(this, EnternetActivity::class.java)

            finish()
            startActivity(intetn)
        }

    }
    //Получения списка пациентов
    fun GetCoursesSportNo(id_patient:Int) {
        if (enternetCheck.isOnline(this)) {
            initRetrofit()
            val Tokens = prefDoctorConclusion.conclusionToken(this)
            CoroutineScope(Dispatchers.IO).launch {
                val sportEdit = doctorApi.GetCoursesSportNo("Bearer $Tokens",id_patient)
                runOnUiThread {

                    //Фиксируем полученные данные
                    val List = sportEdit.body()
                    val Nice = sportEdit.isSuccessful
                    val Code = sportEdit.code()
                    if(Code==429){
                        val intetn = Intent(this@PatientActivity, Code429Activity::class.java)

                        startActivity(intetn)
                    }
                    else if(Code==200) {
                        //Если нету ошибок
                        if (Nice) {
                            if (List != null) {
                                modelDoctor.EditSportListNo.value = List.set_of_sports_exercises_no

                            }
                        }
                    }
                    else if (Code == 500) {
                        val intetn = Intent(this@PatientActivity, Code500Activity::class.java)

                        startActivity(intetn)
                    }
                    else if (Code == 401) {
                        val intetn = Intent(this@PatientActivity, 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, 10000) {
            this@PatientActivity?.runOnUiThread {
                QBAPatientList(idPatient)

            }
        }

    }


}