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

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 androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.FragmentActivity
import androidx.fragment.app.activityViewModels
import com.example.doctor.Adapter.VpAdapter
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.Pref.ClearPref
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.Setting.Courses.Adapter.CoursesDoctorAdapter
import com.example.doctor.Setting.Courses.EditCourses.TabLayoutEditCourses.AllSportCoursesDoctorFragment
import com.example.doctor.Setting.Courses.EditCourses.TabLayoutEditCourses.YourSportCoursesDoctorFragment
import com.example.doctor.databinding.FragmentEditCoursesBinding
import com.google.android.material.tabs.TabLayoutMediator
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 EditCoursesFragment : Fragment() {
    private lateinit var binding:FragmentEditCoursesBinding
    private val model: DoctorViewModel by activityViewModels()
    private lateinit var doctorApi: DoctorApi
    lateinit var adapter: CoursesDoctorAdapter
    val prefDoctorConclusion = ConclusionPref()
    val prefDoctorClear = ClearPref()
    val prefDoctorSave = SavePref()

    private val tList = listOf(
        "добавленные",
        "Все",
    )

    //Список с фрагментами для переключения
    private val flist = listOf(
        YourSportCoursesDoctorFragment.newInstance(),
        AllSportCoursesDoctorFragment.newInstance(),

    )


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

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

            binding.btnBack.setOnClickListener{
                activity?.supportFragmentManager?.beginTransaction()?.replace(R.id.CLCoursesActivity, CreateCoursesFragment.newInstance())?.commit()//Заменяем наш экран на фрагмент (используем наш экран как основу)//R.id.placeHolder - куда всталяем //MainFragment.newInstance() - это то что мы вставляем

            }

            model.CoursesCustomDoctor.observe(viewLifecycleOwner){
                txtNameCourses.text = it.name
                GetEditCourseDoctorYour(it.id)
                GetEditCourseDoctorAll(it.id)
            }
        }
    }

    //Получения списка упражнений созданных врачем
    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

                            }
                        }
                    }
                    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)
        }

    }


    //Функция подключения переключения
    private fun init() = with(binding) {
        val adapter = VpAdapter(activity as FragmentActivity, flist)
        vpCourses.adapter = adapter

        //Переключения (связываем таблаяут(переключатель) с viewpager, чтобы переключать фрагменты)
        TabLayoutMediator(tabLayoutCourses, vpCourses) { tab, pos ->
            tab.text =
                tList[pos]//tab - нажатая кнопка, pos - позиция кнопки, tList[pos] - передаем название по полученной позиции
        }.attach()// attach() - чтобы все переключалось, а не вывадило постоянно один экран

        //Изменения цвета в зависомости на каком из tabLayout вы находитесь
        binding.tabLayoutCourses.setTabTextColors(
            getResources().getColor(R.color.black),
            getResources().getColor(R.color.white)
        );


    }

    //Инициализируем 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)

    }

    //Проверка интернета
    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
    }


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