package com.example.doctor.Patients.TabLayoutPatient

import android.content.Intent
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import androidx.fragment.app.activityViewModels
import androidx.recyclerview.widget.GridLayoutManager
import com.example.doctor.Auth.AuthActivity
import com.example.doctor.CodeError.Code429Activity
import com.example.doctor.CodeError.Code500Activity
import com.example.doctor.DataModel
import com.example.doctor.DoctorViewModel
import com.example.doctor.Enternet.EnternetActivity
import com.example.doctor.Enternet.EnternetCheck
import com.example.doctor.Patients.Adapter.PatientListAdapter
import com.example.doctor.Patients.Model.PatientAllModel
import com.example.doctor.Patients.Model.PatientIdModel
import com.example.doctor.Patients.PatientActivity
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.FragmentActiveCoursesPatientBinding
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


class ActiveCoursesPatientFragment : Fragment(),PatientListAdapter.Listener {
    private lateinit var binding:FragmentActiveCoursesPatientBinding
    private val modelDoctor: DoctorViewModel by activityViewModels()
    private val dataModel: DataModel by activityViewModels()//Для передачи данных
    lateinit var adapterPatient: PatientListAdapter
    private lateinit var doctorApi: DoctorApi
    val prefDoctorConclusion = ConclusionPref()
    val prefDoctorClear = ClearPref()
    val prefDoctorSave = SavePref()

    //Класс проверки интеренета
    val enternetCheck = EnternetCheck()

    var patientYesList:List<PatientAllModel>?=null

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = FragmentActiveCoursesPatientBinding.inflate(layoutInflater,container,false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initRcViewDay()
        GetPatientList()

        modelDoctor.PatientActiveList.observe(viewLifecycleOwner){
            if(patientYesList!=it){
                patientYesList=it
                adapterPatient.submitList(it)
            }
        }
    }

    //Инициализация списка
    private fun initRcViewDay() = with(binding) {
        rcView.layoutManager =
            GridLayoutManager(requireContext(), 1)//По вертикали будет выводить по умолчанию
        adapterPatient = PatientListAdapter(this@ActiveCoursesPatientFragment)
        rcView.adapter = adapterPatient
    }

    //Инициализируем 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)

    }
    //Получения списка пациентов
    fun GetPatientList() {
        if (enternetCheck.isOnline(requireContext())) {
            initRetrofit()
            val Tokens = prefDoctorConclusion.conclusionToken(requireContext())
            CoroutineScope(Dispatchers.IO).launch {
                val listProduct = doctorApi.GetPatientAllActive("Bearer $Tokens")
                requireActivity().runOnUiThread {

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

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

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

                        startActivity(intetn)
                    }
                    else if (Code == 401) {
                        val intetn = Intent(requireContext(), AuthActivity::class.java)
                        activity?.finish()
                        startActivity(intetn)
                    }
                }

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

    }


    companion object {
        fun newInstance() = ActiveCoursesPatientFragment()
    }

    override fun onClickPatient(item: PatientAllModel) {

        //Вывод фрагмента на активити при первоначальной загрузке
//        activity?.supportFragmentManager?.beginTransaction()
//            ?.replace(com.example.doctor.R.id.CLMainPatient, PatientFragment.newInstance())
//            ?.commit()
//        prefDoctorSave.saveIdPatient(requireContext(),item.id!!)
//        prefDoctorSave.saveViewPatient(requireContext(),1)
        //modelDoctor.patientId.value = PatientIdModel(item.id!!)

        prefDoctorSave.saveIdPatient(requireContext(),item.id!!)
        prefDoctorSave.saveViewPatient(requireContext(),1)
        val intetn = Intent(requireContext(), PatientActivity::class.java)
        startActivity(intetn)


       // dataModel.patientList.value = 1
    }
}