package net.bradball.android.androidapptemplate.ui

import android.os.Bundle
import android.view.*
import androidx.constraintlayout.motion.widget.MotionLayout
import androidx.navigation.fragment.findNavController
import androidx.viewpager2.widget.ViewPager2
import dagger.android.support.DaggerFragment

import net.bradball.android.androidapptemplate.R

class ConstraintFragment : DaggerFragment() {

    private lateinit var viewPager: ViewPager2

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val view = inflater.inflate(R.layout.fragment_constraint, container, false)

        viewPager = view.findViewById(R.id.view_pager)

        setupViewPager()

        return view
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        setHasOptionsMenu(true)
    }

    override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
        inflater.inflate(R.menu.options_menu, menu)
    }

    override fun onPrepareOptionsMenu(menu: Menu) {
        super.onPrepareOptionsMenu(menu)

        menu.findItem(R.id.motion_toggle)?.isVisible = false
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return when (item.itemId) {
            R.id.constraint_toggle -> navToMotionFragment()
            else -> super.onOptionsItemSelected(item)
        }
    }

    private fun setupViewPager() {
        // Create a ViewPager Adapter to load Race Fragments.
        val viewPagerAdapter = FragmentViewPagerAdapter(listOf(1, 2, 3), this)

        // Setup the ViewPager.
        viewPager.apply {
            offscreenPageLimit = 1
            adapter = viewPagerAdapter
            setCurrentItem(1, false)
        }
    }

    private fun navToMotionFragment(): Boolean {
        findNavController().popBackStack()
        return true
    }
}
