package com.example.doctor.Patients.Reports.Courses.TabLayout

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.Toast
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.DoctorViewModel
import com.example.doctor.Enternet.EnternetActivity
import com.example.doctor.Enternet.EnternetCheck
import com.example.doctor.Patients.Reports.Courses.CoursesYouAdapter
import com.example.doctor.Patients.Reports.Courses.SportCoursModel
import com.example.doctor.Pref.ClearPref
import com.example.doctor.Pref.ConclusionPref
import com.example.doctor.Pref.SavePref
import com.example.doctor.Retrofit.DoctorApi
import com.example.doctor.Setting.Courses.Model.CoursesDoctorModel
import com.example.doctor.Toast.showCustomInfoToast
import com.example.doctor.databinding.FragmentCoursesYouBinding
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 CoursesYouFragment : Fragment(),CoursesYouAdapter.Listener {
    private lateinit var binding:FragmentCoursesYouBinding
    private val modelDoctor: DoctorViewModel by activityViewModels()
    lateinit var adapterCours: CoursesYouAdapter
    private lateinit var doctorApi: DoctorApi
    val prefDoctorConclusion = ConclusionPref()
    val prefDoctorClear = ClearPref()
    val prefDoctorSave = SavePref()
    var sportCoursesDoctor:List<SportCoursModel>?=null
    var id: Int? = null

    //Класс проверки интеренета
    val enternetCheck = EnternetCheck()
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = FragmentCoursesYouBinding.inflate(layoutInflater,container,false)
        return binding.root
    }

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

        modelDoctor.id_patient.observe(viewLifecycleOwner){
            id = it
            GetCoursesDoctor()
        }

        modelDoctor.SportCoursDoctorList.observe(viewLifecycleOwner){
            if(sportCoursesDoctor!=it){
                sportCoursesDoctor = it
                adapterCours.submitList(it)
                binding.txtNull.visibility = View.GONE
            }
        }
    }

    //Получения списка курсов созданных доктором
    fun GetCoursesDoctor() {
        if (enternetCheck.isOnline(requireContext())) {
            binding.txtNull.visibility = View.VISIBLE
            initRetrofit()
            val Tokens = prefDoctorConclusion.conclusionToken(requireContext())
            CoroutineScope(Dispatchers.IO).launch {
                val listCoursesDoctor = doctorApi.GetCoursesDoctorPatient("Bearer $Tokens",id!!)

                requireActivity().runOnUiThread {


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

                        startActivity(intetn)
                    }
                    else if(Code==200) {
                        //Если нету ошибок
                        if (Nice) {
                            if (List != null) {
                                modelDoctor.SportCoursDoctorList.value = List.courses_doctor
                                binding.txtNull.visibility = View.GONE
                            }
                        }
                    }
                    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)
        }

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

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

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



    override fun onClickCourses(item: SportCoursModel) {
        AddSportPatient(id!!,item.id,14)
        GetCoursesDoctor()
    }

    fun AddSportPatient(id_patient:Int,id_course:Int,all_day:Int){
        if (enternetCheck.isOnline(requireContext())) {
            initRetrofit()
            val Tokens = prefDoctorConclusion.conclusionToken(requireContext())
            CoroutineScope(Dispatchers.IO).launch {
                val updatePassword= doctorApi.AddSportPatient("Bearer $Tokens",id_patient,id_course,all_day)
                requireActivity().runOnUiThread {

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

                        startActivity(intetn)
                    }
                    else if(Code==200) {
                        //Если нету ошибок
                        if (Nice) {
                            if (List != null) {
                                Toast(requireContext()).showCustomInfoToast(List.message, requireActivity())
                                GetCoursesDoctor()
                                modelDoctor.BtnSportCoursDoctorCurrent.value = 2
                            }
                        }
                    }
                    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)
        }

    }
}