package com.example.doctor.Appeals.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 androidx.fragment.app.activityViewModels
import androidx.recyclerview.widget.GridLayoutManager
import com.example.doctor.Appeals.AppealsOldAdapter
import com.example.doctor.Appeals.TabLayout.Model.AppealsNewModel
import com.example.doctor.Appeals.TabLayout.Model.AppealsOldModel
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.Model.PatientIdModel
import com.example.doctor.Patients.PatientActivity
import com.example.doctor.Patients.PatientsListFragment
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.FragmentOldAppealsBinding
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
import kotlin.concurrent.fixedRateTimer


class OldAppealsFragment : Fragment(), AppealsOldAdapter.Listener,AppealsOldAdapter.Listener2 {
    private lateinit var binding:FragmentOldAppealsBinding
    private val model: DoctorViewModel by activityViewModels()
    private val dataModel: DataModel by activityViewModels()//Для передачи данных

    lateinit var adapter: AppealsOldAdapter
    private lateinit var doctorApi: DoctorApi
    val prefDoctorConclusion = ConclusionPref()
    val prefDoctorSave = SavePref()

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

    //Список прочитанных соощений
    var oldAppeals: List<AppealsOldModel>? = null

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

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        //binding.CLNull.visibility = View.VISIBLE

        initRcViewAppeals()
        appealsAllCurrent()
        model.appealsOldList.observe(viewLifecycleOwner) {//viewLifecycleOwner - следит за циклом жизни fragment
            if(oldAppeals != it){

                oldAppeals = it
                adapter.submitList(it)//Напрямую переадем созданный список в adapter(ProductAdapter)
                if(oldAppeals !=null){
                    binding.CLNull.visibility = View.GONE
                    binding.txtNull.visibility = View.GONE
                }
            }
        }

        getOldAppeals()

//        fixedRateTimer("timer", false, 0, 10000) {
//            activity?.runOnUiThread {
//
//            }
//        }
    }

    private fun getOldAppeals() {
        if (enternetCheck.isOnline(requireContext())) {
            initRetrofit()
            val Tokens = prefDoctorConclusion.conclusionToken(requireContext())
            CoroutineScope(Dispatchers.IO).launch {
                val listAppeals = doctorApi.GetAppealsDoctorOld("Bearer $Tokens")
                requireActivity().runOnUiThread {

                    //Фиксируем полученные данные
                    val List = listAppeals.body()
                    val Nice = listAppeals.isSuccessful
                    val Code = listAppeals.code()
                    if(Code==429){
                        val intetn = Intent(requireContext(), Code429Activity::class.java)
                        startActivity(intetn)
                    }
                    else if(Code==200) {
                        //Если нету ошибок
                        if (Nice) {
                            //Если нету ошибок
                            if (List != null) {
                                if(List.appeals_old != null){
                                    //binding.CLNull.visibility = View.GONE
                                    binding.txtNull.visibility = View.GONE
                                    model.appealsOldList.value = List.appeals_old
                                }
                                else{
                                    //binding.CLNull.visibility = View.VISIBLE
                                    binding.txtNull.visibility = View.VISIBLE
                                }
                            }else{
                               // binding.CLNull.visibility = View.VISIBLE
                                binding.txtNull.visibility = View.VISIBLE
                            }
                        }
                    }
                    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 appealsAllCurrent() = with(binding) {
//        model.appealsAllCurrent.observe(viewLifecycleOwner) {//viewLifecycleOwner - следит за циклом жизни fragment
//
//        }

    }

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

        fun newInstance() = OldAppealsFragment()
    }

    override fun onClickAppeals(item: AppealsOldModel) {

    }

    override fun onClickAppealsPatient(item: AppealsOldModel) {
//        prefDoctorSave.saveIdPatient(requireContext(),item.id_patient)
//        prefDoctorSave.saveViewPatient(requireContext(),1)
        model.patientId.value = PatientIdModel(item.id)
       // dataModel.patientAppeal.value = item.id_patient
        val intetn = Intent(requireContext(), PatientActivity::class.java)
        startActivity(intetn)
    }
}