package com.example.doctor.Setting

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 android.widget.Toast
import androidx.appcompat.app.AlertDialog
import com.example.doctor.Auth.AuthActivity
import com.example.doctor.Auth.AuthFragment
import com.example.doctor.CodeError.Code429Activity
import com.example.doctor.CodeError.Code500Activity
import com.example.doctor.Enternet.EnternetActivity
import com.example.doctor.Enternet.EnternetCheck
import com.example.doctor.Enternet.EnternetFragment
import com.example.doctor.MainActivity
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.Setting.Courses.CoursesActivity
import com.example.doctor.Toast.showCustomInfoToast
import com.example.doctor.databinding.FragmentSettingBinding
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 SettingFragment : Fragment() {
    private lateinit var binding:FragmentSettingBinding

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

    //Класс проверки интеренета
    val enternetCheck = EnternetCheck()
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = FragmentSettingBinding.inflate(layoutInflater,container,false)
        return binding.root
    }

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


        button()
    }

    private fun button() = with(binding) {
        btnLogout.setOnClickListener{

            createAlеrtDialogExitAuth()
        }

        btnYourData.setOnClickListener{
            activity?.supportFragmentManager?.beginTransaction()
                ?.replace(R.id.CLMainFragment, YourDataFragment.newInstance())
                ?.commit()
        }

        binding.btnAddCourses.setOnClickListener{
            val intetn = Intent(requireContext(), CoursesActivity::class.java)
            startActivity(intetn)
        }



    }


    //Диалоговое окно
    private fun createAlеrtDialogExitAuth() {
        val builder = AlertDialog.Builder(requireContext())
        builder.setTitle("Выход")
        builder.setMessage("Вы уверены что хотите выйти из аккаунта")
        builder.setNegativeButton("Назад") { dialogInterface, i ->

        }
        builder.setPositiveButton("Подтвердить") { dialogInterface, i ->

            Logout()

        }
        builder.show()
    }

    //Получения списка пациентов
    fun Logout() {
        if (enternetCheck.isOnline(requireContext())) {
        initRetrofit()
        val Tokens = prefDoctorConclusion.conclusionToken(requireContext())
        CoroutineScope(Dispatchers.IO).launch {
            val listProduct = doctorApi.LogoutDoctor("Bearer $Tokens")

            activity?.runOnUiThread {


                //Фиксируем полученные данные
                val List = listProduct.body()
                val Nice = listProduct.isSuccessful
                val Code = listProduct.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.toString(), requireActivity())
                            prefDoctorClear.clearToken(requireContext())
                            activity?.supportFragmentManager?.beginTransaction()
                                ?.replace(R.id.CLMain, AuthFragment.newInstance())
                                ?.commit()
                        }
                    }
                }
                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() = SettingFragment()
    }
}