package com.example.doctor.Home

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 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.Pref.ClearPref
import com.example.doctor.Pref.ConclusionPref
import com.example.doctor.R
import com.example.doctor.Retrofit.DoctorApi
import com.example.doctor.databinding.FragmentHomeBinding
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 HomeFragment : Fragment() {
    private lateinit var binding: FragmentHomeBinding
    private val dataModel: DataModel by activityViewModels()//Для передачи данных

    private var Token = ""
    val prefDoctorClear= ClearPref()
    private lateinit var doctorApi: DoctorApi
    val prefDoctorConclusion = ConclusionPref()
    private val modelDoctor: DoctorViewModel by activityViewModels()

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

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

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

        binding.CVPatinet.setOnClickListener {
            dataModel.fragmentMenu.value = R.id.patient
        }

        binding.CVAppeals.setOnClickListener {
            dataModel.fragmentMenu.value = R.id.list_check
        }

        CountPatientAndAppeals()
    }

    //Получение данных для главной страницы
    fun CountPatientAndAppeals() = with(binding) {
        if (enternetCheck.isOnline(requireContext())) {
            initRetrofit()
            val Tokens = prefDoctorConclusion.conclusionToken(requireContext())
            CoroutineScope(Dispatchers.IO).launch {
                val listHomeView = doctorApi.CountPatientAndAppeals("Bearer $Tokens")

                requireActivity().runOnUiThread {


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

                        startActivity(intetn)
                    }
                    else if(Code==200) {
                        //Если нету ошибок
                        if (Nice) {
                            if (List != null) {
                                txtCountPatient.text = List?.patient.toString()
                                txtCountAppealsNew.text = List?.appeals_check.toString()
                                txtCountAppealsAll.text = List?.appeals_all.toString()
                                CLLoad.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)

    }

    companion object {

        fun newInstance() = HomeFragment()
    }
}