package com.example.smartlab.fragments

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.smartlab.R
import com.example.smartlab.adapters.CatalogAdapter
import com.example.smartlab.adapters.NewsAdapter
import com.example.smartlab.api.MyAPI
import com.example.smartlab.databinding.FragmentAnalyzesBinding
import com.example.smartlab.models.BtnsForCatalog
import com.example.smartlab.models.Catalog
import com.google.gson.Gson
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import okhttp3.OkHttpClient
import okhttp3.internal.wait
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.awaitResponse
import retrofit2.converter.gson.GsonConverterFactory
import java.util.Locale.Category


class AnalyzesFragment : Fragment() {

    private var _binding: FragmentAnalyzesBinding? = null
    private val binding get() = _binding!!


    private var _myListCatalog: List<Catalog>? = null

    private val catalogList get() = _myListCatalog!!

    private lateinit var myAdapterNews: NewsAdapter
    private lateinit var myAdapterCatalog: CatalogAdapter
    private lateinit var myAdapterBtnsForCatalog: BtnsForCatalog


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        _binding = FragmentAnalyzesBinding.inflate(inflater, container, false)
        val view  = binding.root


        // News adapter

        myAdapterNews = NewsAdapter(requireContext())
        binding.newsContainer.layoutManager = LinearLayoutManager(requireContext(),
            LinearLayoutManager.HORIZONTAL, false)
        binding.newsContainer.adapter = myAdapterNews

        val interceptor = HttpLoggingInterceptor()
        interceptor.level = HttpLoggingInterceptor.Level.BODY

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

        val retrofit = Retrofit.Builder()
            .baseUrl(getString(R.string.api_root)).client(client)
            .addConverterFactory(GsonConverterFactory.create()).build()


        val myAPI = retrofit.create(MyAPI::class.java)

        CoroutineScope(Dispatchers.IO).launch {
            val list = myAPI.getNews()


            val response = list.awaitResponse()
            if (response.isSuccessful){
                activity?.runOnUiThread(Runnable{
                    binding.apply {
                        myAdapterNews.submitList(response.body())
                    }

                })
            }

        }


        // Catalog adapter

        myAdapterCatalog = CatalogAdapter()
        binding.catalogContainer.layoutManager = LinearLayoutManager(requireContext(),
            LinearLayoutManager.VERTICAL, false)
        binding.catalogContainer.adapter = myAdapterCatalog

        CoroutineScope(Dispatchers.IO).launch {
            val listCatalog  = myAPI.getCatalog()
            val responseForCatalog = listCatalog.execute()

            if (responseForCatalog.isSuccessful){
                _myListCatalog =   responseForCatalog.body()

                activity?.runOnUiThread(Runnable {
                    binding.apply {
                        var newList: List<Catalog> = catalogList.filter {
                            s -> s.category == "Популярные"
                        }
                        myAdapterCatalog.submitList(newList)
                    }
                })

            }
        }


        // Btns

        val btns = arrayListOf("Популярные", "COVID", "Онкогенетические",
        "ЗОЖ")




        //   TODO: Подтягивание из Апи информации и макет



//        binding.newsContainer.layoutManager = LinearLayoutManager(requireContext())
//        binding.newsContainer.adapter = adapter
//        adapter.submitList()




        return view


        //        inflater.inflate(R.layout.fragment_analyzes, container, false)
    }


}