package com.hanwha.morakmorak.ui.main.home

import android.content.Intent
import android.os.Bundle
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import com.google.android.material.snackbar.Snackbar
import com.hanwha.morakmorak.R
import com.hanwha.morakmorak.databinding.FragmentHomeBinding
import com.hanwha.morakmorak.ui.BindingFragment
import com.hanwha.morakmorak.ui.main.MainActivity
import com.hanwha.morakmorak.ui.main.home.detail.HomeDetailActivity
import kotlinx.android.synthetic.main.fragment_home.*
import org.koin.androidx.viewmodel.ext.android.getViewModel
import timber.log.Timber


/**
 * A simple [Fragment] subclass.
 * Activities that contain this fragment must implement the
 * [HomeFragment.OnFragmentInteractionListener] interface
 * to handle interaction events.
 * Use the [HomeFragment.newInstance] factory method to
 * create an instance of this fragment.
 *
 */
class HomeFragment : BindingFragment<FragmentHomeBinding>() {

    override fun getLayoutResId() = R.layout.fragment_home

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        binding.run {
            lifecycleOwner = this@HomeFragment

            vm = getViewModel<HomeViewModel>().apply {
                isRefresh.observe(this@HomeFragment, Observer { isRefresh ->
                    if (isRefresh!!) {
                        binding.vm!!.requestParties()
//                        Handler().postDelayed({
//                            home_pullToRefreshView.setRefreshing(!isRefresh)
//                            binding.vm!!.isRefresh.value = false
//                        }, 2000)
                    } else {
                        home_pullToRefreshView.setRefreshing(false)
                    }
                })

                goDetail = { view ->
                    Timber.i("${view.id}.goDetail!!!")
                    Timber.i("${view.tag}.PatyId")
                    val intent = Intent(activity, HomeDetailActivity::class.java).apply { putExtra(EXTRA_PARTY_ID, view.tag as Int) }
                    startActivity(intent)
                }

                updateList = {
                    binding.homeRecyclerView.adapter?.notifyDataSetChanged()
                }

                onDistanceClick = {
                    Snackbar.make(
                            binding.snackbarCoordinatorLayout,
                            "기능을 사용하려면 500만원을 입금해주세요.",
                            Snackbar.LENGTH_SHORT)
                            .show()
                }

                isProgressVisible.observe(this@HomeFragment, Observer { (activity as MainActivity).showLoadingProgress(it)})
            }
        }
    }

    override fun onStart() {
        super.onStart()
        binding.vm!!.requestParties()
    }

    companion object {
        const val EXTRA_PARTY_ID = "morakmorak.intent.extra.PARTY_ID"
    }

}
