package com.gh.gamecenter.qa.article

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.MenuItem
import android.view.View
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.RecyclerView
import com.gh.gamecenter.R
import com.gh.gamecenter.common.baselist.ListFragment
import com.gh.gamecenter.common.baselist.LoadType
import com.gh.gamecenter.common.baselist.NormalListViewModel
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.utils.checkStoragePermissionBeforeAction
import com.gh.gamecenter.common.utils.ifLogin
import com.gh.gamecenter.common.utils.toColor
import com.gh.gamecenter.common.utils.toDrawable
import com.gh.gamecenter.common.view.CustomDividerItemDecoration
import com.gh.gamecenter.login.user.UserManager
import com.gh.gamecenter.qa.article.edit.ArticleEditActivity
import com.gh.gamecenter.feature.entity.ArticleEntity
import com.gh.gamecenter.retrofit.RetrofitManager
import com.halo.assistant.HaloApp
import io.reactivex.Observable

class MyArticleFragment : ListFragment<ArticleEntity, NormalListViewModel<ArticleEntity>>() {

    private var mTargetUserId = ""
    private var mAdapter: MyArticleAdapter? = null

    override fun provideListAdapter(): MyArticleAdapter {
        if (mAdapter == null) {
            val path = if (mTargetUserId == UserManager.getInstance().userId) {
                "我的帖子"
            } else {
                "Ta的帖子"
            }
            mAdapter = MyArticleAdapter(requireContext(), mEntrance, path)
        }
        return mAdapter!!
    }

    override fun provideDataObservable(page: Int): Observable<MutableList<ArticleEntity>>? {
        return RetrofitManager.getInstance().api.getMyArticleAndQuestion(mTargetUserId, page)
            .flatMap { list ->
                Observable.create { emitter ->
                    val articleList = list.map { it.transformArticleEntity() }.toMutableList()
                    emitter.onNext(articleList)
                    emitter.onComplete()
                }
            }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == MyArticleActivity.PUBLISH_ARTICLE_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
            mListViewModel.load(LoadType.REFRESH)
        }
    }

    override fun provideListViewModel(): NormalListViewModel<ArticleEntity> {
        val factory = NormalListViewModel.Factory(HaloApp.getInstance().application, this)
        return ViewModelProviders.of(this, factory)
            .get(NormalListViewModel::class.java) as NormalListViewModel<ArticleEntity>
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        mTargetUserId = arguments?.getString(EntranceConsts.KEY_USER_ID) ?: ""
        super.onCreate(savedInstanceState)

        if (activity is MyArticleActivity) {
            if (mTargetUserId == UserManager.getInstance().userId) {
                setNavigationTitle("我的帖子")
                initMenu(R.menu.menu_article_publich)
            } else {
                setNavigationTitle("Ta的帖子")
            }
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        mCachedView.setBackgroundColor(R.color.background_white.toColor(requireContext()))
    }

    override fun onMenuItemClick(item: MenuItem?) {
        if (item?.itemId == R.id.menu_article_publish) {
            ifLogin("个人主页-Ta的文章-发文章") {
                checkStoragePermissionBeforeAction {
                    startActivityForResult(
                        ArticleEditActivity.getIntent(requireContext()),
                        MyArticleActivity.PUBLISH_ARTICLE_REQUEST_CODE
                    )
                }
            }
        }
    }

    override fun addSyncPageObserver(): Boolean {
        return true
    }

    override fun provideSyncAdapter(): MyArticleAdapter? {
        return mAdapter
    }

    override fun getItemDecoration(): RecyclerView.ItemDecoration {
        val itemDecoration = CustomDividerItemDecoration(
            requireContext(),
            onlyDecorateTheFirstItem = false,
            notDecorateTheFirstItem = false,
            notDecorateTheLastItem = true,
            notDecorateTheFirstTwoItems = false
        )
        itemDecoration.setDrawable(R.drawable.divider_item_line_space_16.toDrawable(requireContext())!!)
        return itemDecoration
    }

    override fun onDarkModeChanged() {
        super.onDarkModeChanged()
        if (mListRv != null && mListRv.itemDecorationCount > 0) {
            mListRv.removeItemDecorationAt(0)
            mListRv.addItemDecoration(itemDecoration)
        }
    }

    companion object {
        @JvmStatic
        fun getInstance(entrance: String?, userId: String): MyArticleFragment {
            val fragment = MyArticleFragment()
            val args = Bundle()
            args.putString(EntranceConsts.KEY_ENTRANCE, entrance)
            args.putString(EntranceConsts.KEY_USER_ID, userId)
            fragment.arguments = args
            return fragment
        }
    }
}