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

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.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.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;

    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){
            adapterYes.submitList(it)
        }
    }


    //Инициализация списка
    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("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
                    binding.txtYes.visibility = View.GONE
                }
                else{
                    binding.txtYes.visibility = View.VISIBLE
                }
            }

        }
    }
    //Получения списка пациентов
    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)
                }
            }

        }
    }


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

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

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


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

    override fun onClickAppeals(item: EditSportModel) {
        UpdateBlockSportTasksYes(id_patient, item.id)

    }
}