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

import android.content.Intent
import android.os.Bundle
import android.util.Log
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.Edit.EditSportYesAdapter
import com.example.doctor.Patients.Reports.Edit.EditSportModel
import com.example.doctor.Patients.Reports.Edit.EditSportNoAdapter
import com.example.doctor.Pref.ConclusionPref
import com.example.doctor.Retrofit.DoctorApi
import com.example.doctor.Toast.showCustomInfoToast
import com.example.doctor.databinding.FragmentEditSportYesBinding
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 EditSportYesFragment : Fragment(), EditSportYesAdapter.Listener {
    private lateinit var binding:FragmentEditSportYesBinding
    lateinit var adapterYes: EditSportYesAdapter
    private lateinit var doctorApi: DoctorApi
    val prefDoctorConclusion = ConclusionPref()
    private val model: DoctorViewModel by activityViewModels()
    var id_patient = 0;
    var editYes:List<EditSportModel>?=null

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


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


        model.id_patient.observe(viewLifecycleOwner) {id->
            id_patient = id.toInt()
            Log.i("id_patient",id_patient.toString())
            Log.i("id",id.toString())
            GetCoursesSportYes(id_patient)
        }

        model.EditSportListYes.observe(viewLifecycleOwner){
            if(it!=null){
                if(editYes!=it){
                    editYes=it
                    adapterYes.submitList(it)
                    binding.txtYes.visibility = View.GONE
                }
            }
            else{
                binding.txtYes.visibility = View.GONE
            }


        }
        btnClick()
    }

    private fun btnClick()=with(binding) {
        CLLoad.setOnClickListener {  }
    }


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



    //Инициализируем 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 GetCoursesSportYes(id_patient:Int)=with(binding) {
        if (enternetCheck.isOnline(requireContext())) {
            initRetrofit()
            val Tokens = prefDoctorConclusion.conclusionToken(requireContext())
            CoroutineScope(Dispatchers.IO).launch {
                val sportEdit = doctorApi.GetCoursesSportYes("Bearer $Tokens", id_patient)
                requireActivity().runOnUiThread {

                    //Фиксируем полученные данные
                    val List = sportEdit.body()
                    val Nice = sportEdit.isSuccessful
                    val Code = sportEdit.code()
                    if(Code==429){
                        CLLoad.visibility = View.GONE

                        val intetn = Intent(requireContext(), Code429Activity::class.java)

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

                                binding.txtYes.visibility = View.VISIBLE
                                binding.rcViewEditSportYes.visibility = View.GONE
                                binding.CLLoad.visibility = View.GONE
                            }
                        }
                        else{
                            CLLoad.visibility = View.GONE
                        }
                    }
                    else if(Code==500){
                        CLLoad.visibility = View.GONE
                        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{
                        CLLoad.visibility = View.GONE
                    }

                    //Фиксируем полученные данные
                    val sportEditList = sportEdit.body()

                    //Если нету ошибок

                }

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

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


                    //Фиксируем полученные данные
                    val List = sportEdit.body()
                    val Nice = sportEdit.isSuccessful
                    val Code = sportEdit.code()
                    if(Code==429){
                        CLLoad.visibility = View.GONE

                        val intetn = Intent(requireContext(), Code429Activity::class.java)

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

                }

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

    }


    //Отключение упражнения
    fun UpdateBlockSportTasksYes(id_pateint:Int,id_sports_tasks:Int)=with(binding) {
        if (enternetCheck.isOnline(requireContext())) {
            initRetrofit()
            val Tokens = prefDoctorConclusion.conclusionToken(requireContext())
            CoroutineScope(Dispatchers.IO).launch {
                val sportEdit = doctorApi.UpdateBlockSportTasksYes("Bearer $Tokens", id_pateint,id_sports_tasks)
                requireActivity().runOnUiThread {

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

                        startActivity(intetn)
                    }
                    else if(Code==200){
                        //Если нету ошибок
                        if(Nice){
                            if (List != null) {
                                Toast(requireContext()).showCustomInfoToast(List.message, requireActivity())
                                GetCoursesSportYes(id_patient)
                                GetCoursesSportNo(id_patient)

                            }
                            else{
                                if (List != null) {
                                    Toast(requireContext()).showCustomInfoToast(List.message, requireActivity())
                                    CLLoad.visibility = View.GONE
                                }
                                CLLoad.visibility = View.GONE
                            }
                        }
                        else{
                            CLLoad.visibility = View.GONE
                        }
                    }
                    else if(Code==500){
                        CLLoad.visibility = View.GONE
                        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{
                        CLLoad.visibility = View.GONE
                    }

                }
            }


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


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

    override fun onClickAppeals(item: EditSportModel) {
        binding.CLLoad.visibility = View.VISIBLE
        UpdateBlockSportTasksYes(id_patient, item.id)

    }
}