package com.example.doctor.Appeals

import android.content.Intent
import android.os.Bundle
import android.transition.TransitionInflater
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.Toast
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.Patients.Model.PatientAllModel
import com.example.doctor.Patients.Reports.PatientFragment
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.Toast.showCustomInfoToast
import com.example.doctor.databinding.FragmentCreateMessageBinding
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
import java.util.Timer
import kotlin.concurrent.fixedRateTimer


class CreateMessageFragment : Fragment() {
    private lateinit var binding: FragmentCreateMessageBinding
    private val dataModel: DataModel by activityViewModels()//Для передачи данных
    private val modelDoctor: DoctorViewModel by activityViewModels()

    private lateinit var doctorApi: DoctorApi
    private lateinit var timer: Timer


    val prefDoctorConclusion = ConclusionPref()
    val prefDoctorClear = ClearPref()

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

    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val inflater = TransitionInflater.from(requireContext())
        enterTransition = inflater.inflateTransition(R.transition.slide_right)
        exitTransition = inflater.inflateTransition(R.transition.slide_right)

        GetPatientList()

        binding.btnAddMessagePatient.setOnClickListener{
            val login = binding.searchPatient.text.toString()
            val text = binding.edTextMessagePatient.text.toString()
            if(login!="" && text!=""){
                AddMessageDoctor()
            }
            else{
                Toast(requireContext()).showCustomInfoToast("Не все данные заполнены", requireActivity())

            }
        }

//        binding.btnExit.setOnClickListener{
//            dataModel.patientAppeal.value = 1
//        }

        binding.btnExit.setOnClickListener{
            activity?.finish()
        }

        modelDoctor.patientListSearch.observe(viewLifecycleOwner){
            if(patientList!=it){
                patientList =it
                addPatientLogin(it)
            }
        }

//        fixedRateTimer("timer", false, 0, 10000) {
//            activity?.runOnUiThread {
//
//            }
//        }
    }

    private fun addPatientLogin(patient: List<PatientAllModel>) {
        val listPatient = arrayListOf("")
        for(i in 0 .. patient.count()-1){
            listPatient.add(patient[i].login.toString())
        }

        val adapter = ArrayAdapter(requireContext(), android.R.layout.simple_list_item_1, listPatient)

        binding.searchPatient.threshold = 1
        binding.searchPatient.setAdapter(adapter)

        binding.searchPatient.setOnItemClickListener { parent, arg1, pos, id ->
            //val list = ArrayList<PatientModel>()
            val serpat = binding.searchPatient.text.toString()
            binding.searchPatient.setText(serpat)

        }
    }


    //Получения списка пациентов
    fun GetPatientList() {
        if (enternetCheck.isOnline(requireContext())) {
            initRetrofit()
            val Tokens = prefDoctorConclusion.conclusionToken(requireContext())
            CoroutineScope(Dispatchers.IO).launch {
                val listProduct = doctorApi.GetPatientAll("Bearer $Tokens")
                requireActivity().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) {
                                //Если нету ошибок
                                if (List != null) {
                                    modelDoctor.patientListSearch.value =  List.patient
                                }
                            }
                        }
                    }
                    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 AddMessageDoctor() {
        if (enternetCheck.isOnline(requireContext())) {
            initRetrofit()
            val Tokens = prefDoctorConclusion.conclusionToken(requireContext())
            CoroutineScope(Dispatchers.IO).launch {
                val listProduct = doctorApi.AddMessageDoctor("Bearer $Tokens",binding.searchPatient.text.toString(),binding.edTextMessagePatient.text.toString())
                requireActivity().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) {
                                //Если нету ошибок
                                if (List != null) {
                                    Toast(requireContext()).showCustomInfoToast(List.message, requireActivity())
                                    binding.edTextMessagePatient.setText("")
                                }

                            }
                        }
                    }
                    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() = CreateMessageFragment()
    }


    override fun onResume() {
        super.onResume()
        checkForUpdates(true)
    }

    override fun onStop() {
        super.onStop()
        timer.cancel()
        timer.purge()
    }

    private fun checkForUpdates(daemonIsTrue: Boolean) {

        timer = fixedRateTimer("default", daemonIsTrue, 0, 10000) {
            activity?.runOnUiThread {
                GetPatientList()
            }
        }

    }
}