package com.example.doctor.Setting

import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
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.Patients.Reports.PatientFragment
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.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()

    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(com.example.doctor.R.id.CLMainFragment, YourDataFragment.newInstance())
                ?.commit()
        }



    }


    //Диалоговое окно
    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() {
        initRetrofit()
        val Tokens = prefDoctorConclusion.conclusionToken(requireContext())
        CoroutineScope(Dispatchers.IO).launch {
            val listProduct = doctorApi.LogoutDoctor("Bearer $Tokens")

            activity?.runOnUiThread {

                //Фиксируем полученные данные
                val visibleviewList = listProduct.body()
                val visibleviewListCode = listProduct.isSuccessful()
                //Если нету ошибок
                if (visibleviewListCode) {
                    Toast(requireContext()).showCustomInfoToast(visibleviewList?.message.toString(), requireActivity())
                    prefDoctorClear.clearToken(requireContext())
                    activity?.supportFragmentManager?.beginTransaction()
                        ?.replace(R.id.CLMain, AuthFragment.newInstance())
                        ?.commit()


                }
            }
        }
    }
    //Инициализируем Retrofit
    private fun initRetrofit() {
        val interceptor = HttpLoggingInterceptor()
        interceptor.level = HttpLoggingInterceptor.Level.BODY

        val client = OkHttpClient
            .Builder()
            .addInterceptor(interceptor)
            .build()

        val retrofit = Retrofit.Builder()
            .baseUrl("http://mobileapp.vmeda.org/api/")
            .client(client)
            .addConverterFactory(GsonConverterFactory.create())
            .build()

        doctorApi = retrofit.create(DoctorApi::class.java)

    }

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