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

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.DoctorViewModel
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.FragmentEditSportNoBinding
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 EditSportNoFragment : Fragment(),EditSportNoAdapter.Listener {
    private lateinit var binding:FragmentEditSportNoBinding
    lateinit var adapterNo: EditSportNoAdapter
    private lateinit var doctorApi: DoctorApi
    val prefDoctorConclusion = ConclusionPref()
    private val model: DoctorViewModel by activityViewModels()
    var id_patient = 0;



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

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initRcViewDay()
        model.EditSportListNo.observe(viewLifecycleOwner){
            adapterNo.submitList(it)
        }
        model.id_patient.observe(viewLifecycleOwner) {id->
            id_patient = id.toInt()
            GetCoursesSportNo(id_patient)
        }
    }


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

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

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

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

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

    }


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

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

                //Если нету ошибок
                if (sportEditList != null) {
                    model.EditSportListYes.value = sportEditList.set_of_sports_exercises_yes
                    //adapterYes.submitList(sportEditList.set_of_sports_exercises_yes)
                }
            }

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

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

                //Если нету ошибок
                if (sportEditList != null) {
                    model.EditSportListNo.value = sportEditList.set_of_sports_exercises_no
                    //adapterNo.submitList(sportEditList.set_of_sports_exercises_no)
                    binding.txtNo.visibility = View.GONE
                }
                else{
                    binding.txtNo.visibility = View.VISIBLE

                }
            }

        }
    }


    //Получения списка пациентов
    fun UpdateBlockSportTasksNo(id:Int) {
        initRetrofit()
        val Tokens = prefDoctorConclusion.conclusionToken(requireContext())
        CoroutineScope(Dispatchers.IO).launch {
            val NoEdit = doctorApi.UpdateBlockSportTasksNo("Bearer $Tokens", id)
            requireActivity().runOnUiThread {

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

                //Если нету ошибок
                if (sportNoList != null) {
                    Toast(requireContext()).showCustomInfoToast(sportNoList.message, requireActivity())
                    GetCoursesSportYes(id_patient)
                    GetCoursesSportNo(id_patient)

                }
                else{
                    if (sportNoList != null) {
                        Toast(requireContext()).showCustomInfoToast(sportNoList.message, requireActivity())
                    }
                }
            }
        }
    }


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

    override fun onClickAppeals(item: EditSportModel) {

        UpdateBlockSportTasksNo(item.id)

    }
}