package com.medicdigital.jjpodcasts.presentation.leaderboard

import android.nfc.tech.MifareUltralight.PAGE_SIZE
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CircleCrop
import com.bumptech.glide.request.RequestOptions
import com.medicdigital.jjpodcasts.NetworkUtils
import com.medicdigital.jjpodcasts.R
import com.medicdigital.jjpodcasts.data.remote.responce.leaderboard.BoardModel
import com.medicdigital.jjpodcasts.presentation.base.BaseFragment
import com.medicdigital.jjpodcasts.presentation.utils.DeviceUtil
import com.medicdigital.jjpodcasts.presentation.utils.setProgressBarColor
import com.medicdigital.jjpodcasts.presentation.utils.setToolbarColor
import dagger.android.support.AndroidSupportInjection
import com.medicdigital.jjpodcasts.databinding.FragmentLeaderboardBinding


class LeaderBoardFragment : BaseFragment() {

    override lateinit var viewModel: LeaderBoardViewModel
    private lateinit var leaderBoardListAdapter: LeaderBoardListAdapter
    private lateinit var layoutManager: LinearLayoutManager

    override fun getMenuButton() = btn_toolbar_fragment_leaderboard_menuButton

    override fun getToolbar() = toolbar_fragment_leaderboard

    private var boardModel: BoardModel? = null

    private val rvScrollListener = object : RecyclerView.OnScrollListener() {
       val elevationActive = DeviceUtil.dp2px(8f)
       override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
          super.onScrolled(recyclerView, dx, dy)
          val visibleItemCount = layoutManager.childCount
          val totalItemCount = layoutManager.itemCount
          val firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition()

          if (viewModel.loadingLiveData.value == false && viewModel.hasMoreItems) {
             if (visibleItemCount + firstVisibleItemPosition >= totalItemCount
                   && firstVisibleItemPosition >= 0
                   && totalItemCount >= PAGE_SIZE) {
                viewModel.loadParticipants(boardModel?.id ?: 0, viewModel.offset)
             }
          }

          if (!recyclerView.canScrollVertically(-1)) {
             wrp_fragment_leaderboard_participant.elevation = 0f
          } else {
             wrp_fragment_leaderboard_participant.elevation = elevationActive
          }
       }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
       AndroidSupportInjection.inject(this)
       super.onCreate(savedInstanceState)
          viewModel = ViewModelProviders.of(this, viewModelFactory)
                .get(LeaderBoardViewModel::class.java)
    }

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

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
       super.onViewCreated(view, savedInstanceState)
       activity?.let { activity ->
          boardModel = arguments?.getParcelable(BOARD)
          val boardId = boardModel?.id ?: 0
          setProgressBarColor(pw_fragment_leaderboard)
          setToolbarColor(toolbar_fragment_leaderboard, activity, activity.window)
          toolbar_fragment_leaderboard.setTitle(boardModel?.name)
          toolbar_fragment_leaderboard.setNavigationOnClickListener {
             activity.onBackPressed()
          }

          layoutManager = LinearLayoutManager(activity, RecyclerView.VERTICAL, false)
          leaderBoardListAdapter = LeaderBoardListAdapter()
          rv_fragment_leaderboard.layoutManager = layoutManager
          rv_fragment_leaderboard.adapter = leaderBoardListAdapter
          rv_fragment_leaderboard.addOnScrollListener(rvScrollListener)
          srl_fragment_leaderboard.setOnRefreshListener {
             viewModel.loadParticipants(boardId)
          }

          viewModel.participantsLiveData.observe(activity, Observer {
             if (viewModel.isInitialData) {
                wrp_fragment_leaderboard_participant.visibility = if (!it.isNullOrEmpty()) View.VISIBLE else View.INVISIBLE
                viewModel.isInitialData = false
                leaderBoardListAdapter.setNewData(it)
             } else {
                leaderBoardListAdapter.addNewData(it)
             }
          })
          viewModel.currentParticipantLiveData.observe(activity, Observer {
             txt_fragment_leaderboard_username.text = it.name
             txt_fragment_leaderboard_rank.text = it.rank.toString()
             txt_fragment_leaderboard_points.text = it.score.toString()

             Glide.with(activity).load(it.url)
                   .apply(RequestOptions().placeholder(R.drawable.ic_microfon_gray).fitCenter())
                   .transform(CircleCrop())
                   .into(iv_fragment_leaderboard_avatar)
          })
          viewModel.refreshLiveData.observe(this, Observer {
             srl_fragment_leaderboard.isRefreshing = it
          })
          viewModel.loadingLiveData.observe(this, Observer {
             pw_fragment_leaderboard.animate().alpha(if (it) 1F else 0F).setDuration(250L).start()
          })
          if (NetworkUtils.isNetworkConnected(activity, false)) {
             viewModel.loadMyParticipantData(boardId)
             viewModel.loadParticipants(boardId)
          } else {
             viewModel.getMyParticipantData(boardId)
             viewModel.getParticipants(boardId)
          }
       }
    }

    companion object {
       const val BOARD = "board"
    }
}