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 MotionFragment : DaggerFragment() {

    private lateinit var motionLayout: MotionLayout
    private lateinit var viewPager: ViewPager2

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        motionLayout = inflater.inflate(R.layout.fragment_motion, container, false) as MotionLayout

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

        setupViewPager()

        return motionLayout
    }

    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 onOptionsItemSelected(item: MenuItem): Boolean {
        return when (item.itemId) {
            R.id.motion_toggle -> toggleMotion()
            R.id.constraint_toggle -> navToConstraintFragment()
            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 toggleMotion(): Boolean {

        when (motionLayout.currentState) {
            R.id.start_state -> motionLayout.transitionToEnd()
            else -> motionLayout.transitionToStart()
        }

        return true
    }

    private fun navToConstraintFragment(): Boolean {
        findNavController().navigate(R.id.constraintFragment)
        return true
    }
}
