package com.example.doctor.Setting.Courses.EditCourses.TabLayoutEditCourses

import android.content.Context
import android.content.Intent
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import android.os.Build
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.EnternetFragment
import com.example.doctor.Pref.ConclusionPref
import com.example.doctor.R
import com.example.doctor.Retrofit.DoctorApi
import com.example.doctor.Setting.Courses.EditCourses.TabLayoutEditCourses.Adapter.EditCoursesDoctorYourAdapter
import com.example.doctor.Setting.Courses.EditCourses.TabLayoutEditCourses.Model.EditCoursesDoctorModel
import com.example.doctor.Toast.showCustomInfoToast
import com.example.doctor.databinding.FragmentYourSportCoursesDoctorBinding
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 YourSportCoursesDoctorFragment : Fragment(), EditCoursesDoctorYourAdapter.Listener {
    private lateinit var binding: FragmentYourSportCoursesDoctorBinding
    lateinit var adapterYour: EditCoursesDoctorYourAdapter
    private lateinit var doctorApi: DoctorApi
    val prefDoctorConclusion = ConclusionPref()
    private val model: DoctorViewModel by activityViewModels()
    var id_patient = 0;
    var id_courses = 0;
    var id_activitis = 0;
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = FragmentYourSportCoursesDoctorBinding.inflate(layoutInflater,container,false)
        return binding.root
    }

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

        model.CoursesCustomDoctor.observe(viewLifecycleOwner){
            id_courses = it.id
            id_activitis = it.id_activity
            GetEditCourseDoctorYour(id_courses)
        }
//        id_courses = prefDoctorConclusion.conclusionIdCourses(requireContext())
//        id_activitis = prefDoctorConclusion.conclusionIdActivitis(requireContext())


        model.EditCoursesDoctorYourList.observe(viewLifecycleOwner){
            adapterYour.submitList(it)
        }
//        model.CoursesDoctorCA.observe(viewLifecycleOwner){
//            id_courses = it.id_courses
//            id_activitis = it.id_activitis
//        }
        Log.i("1sadas","1sadasd")
    }

    override fun onResume() {
        super.onResume()
        Log.i("1sadas","11sadasd")

    }
    //Получения списка курсов созданных доктором
    fun GetEditCourseDoctorYour(id:Int) {
        if (isOnline(requireContext())) {
            initRetrofit()
            val Tokens = prefDoctorConclusion.conclusionToken(requireContext())
            CoroutineScope(Dispatchers.IO).launch {
                val listCoursesDoctor = doctorApi.GetEditCourseDoctorYour("Bearer $Tokens",id)

                requireActivity().runOnUiThread {


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

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

    }

    //Получения списка курсов созданных доктором
    fun GetEditCourseDoctorAll(id:Int) {
        if (isOnline(requireContext())) {
            val Tokens = prefDoctorConclusion.conclusionToken(requireContext())
            CoroutineScope(Dispatchers.IO).launch {
                val listCoursesDoctor = doctorApi.GetEditCourseDoctorAll("Bearer $Tokens",id)

                requireActivity().runOnUiThread {

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

                    //Если нету ошибок
                    if (CoursesDoctorList != null) {
                        model.EditCoursesDoctorAllList.value = CoursesDoctorList.set_of_sports_exercises_all
                    }


                }

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

    }

    //Получения списка курсов созданных доктором
    fun ClearCoursesCreatingDoctor(id:Int) {

        if (isOnline(requireContext())) {
            initRetrofit()
            val Tokens = prefDoctorConclusion.conclusionToken(requireContext())
            CoroutineScope(Dispatchers.IO).launch {
                val listCoursesDoctorYourClear = doctorApi.ClearCoursesCreatingDoctor("Bearer $Tokens",id)

                requireActivity().runOnUiThread {


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

                        startActivity(intetn)
                    }
                    else if(Code==200) {
                        //Если нету ошибок
                        if (Nice) {
                            if (List != null) {
                                Toast(requireContext()).showCustomInfoToast(List.message, requireActivity())
                                GetEditCourseDoctorYour(id_courses)
                                GetEditCourseDoctorAll(id_courses)
                            }
                        }
                    }
                    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)
        }


    }

    //Проверка интернета
    fun isOnline(context: Context): Boolean {
        if (context == null) return false
        val connectivityManager =
            context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            val capabilities =
                connectivityManager.getNetworkCapabilities(connectivityManager.activeNetwork)
            if (capabilities != null) {
                when {
                    capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> {
                        return true
                    }

                    capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> {
                        return true
                    }

                    capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> {
                        return true
                    }
                }
            }
        } else {
            val activeNetworkInfo = connectivityManager.activeNetworkInfo
            if (activeNetworkInfo != null && activeNetworkInfo.isConnected) {
                return true
            }
        }
        return false
    }


    //Инициализируем 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 initRcView() = with(binding) {
        rcView.layoutManager = GridLayoutManager(requireContext(), 1)//По вертикали будет выводить по умолчанию
        adapterYour = EditCoursesDoctorYourAdapter(this@YourSportCoursesDoctorFragment)
        rcView.adapter = adapterYour
    }
    companion object {

        fun newInstance() = YourSportCoursesDoctorFragment()
    }

    override fun onClickCoursesYour(item: EditCoursesDoctorModel) {
        Log.i("sadsadsadasd",item.toString())

        ClearCoursesCreatingDoctor(item.id_exercises)
    }
}