package org.mosad.teapod.ui.activity.main.fragments

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.google.android.material.tabs.TabLayoutMediator
import kotlinx.coroutines.launch
import org.mosad.teapod.R
import org.mosad.teapod.databinding.FragmentMyListsBinding
import org.mosad.teapod.parser.crunchyroll.Crunchyroll
import org.mosad.teapod.util.toItemMediaList

class MyListsFragment : Fragment() {

    private lateinit var binding: FragmentMyListsBinding
    private lateinit var pagerAdapter: FragmentStateAdapter

    private val fragments = arrayListOf<Fragment>()

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

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

        // tab layout and pager
        pagerAdapter = ScreenSlidePagerAdapter(this)
        binding.pagerMyLists.adapter = pagerAdapter

        // TODO is position 0 always episodes? (and 1 always similar titles)
        TabLayoutMediator(binding.tabMyLists, binding.pagerMyLists) { tab, position ->
            tab.text = when(position) {
                0 -> getString(R.string.my_list)
                1 -> getString(R.string.crunchylists)
                2 -> getString(R.string.downloads)
                else -> ""
            }
        }.attach()

        lifecycleScope.launch {
            val items = Crunchyroll.watchlist(50)

            MediaFragmentSimilar(items.toItemMediaList()).also {
                fragments.add(it)
                pagerAdapter.notifyItemInserted(fragments.indexOf(it))
            }
        }

    }

    /**
     * A simple pager adapter
     * TODO also present in MediaFragment
     */
    private inner class ScreenSlidePagerAdapter(fragment: Fragment) : FragmentStateAdapter(fragment) {
        override fun getItemCount(): Int = fragments.size

        override fun createFragment(position: Int): Fragment = fragments[position]
    }

}