package com.gh.gamecenter.qa.article.draft

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import androidx.core.content.ContextCompat
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.RecyclerView
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.core.utils.UrlFilterUtils
import com.gh.gamecenter.common.utils.checkStoragePermissionBeforeAction
import com.gh.gamecenter.common.view.CustomDividerItemDecoration
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.eventbus.EBReuse
import com.gh.gamecenter.login.user.UserManager
import com.gh.gamecenter.qa.article.edit.ArticleEditActivity
import com.gh.gamecenter.qa.draft.CommunityDraftWrapperActivity
import com.gh.gamecenter.qa.entity.ArticleDraftEntity
import com.gh.gamecenter.common.retrofit.Response
import com.gh.gamecenter.retrofit.RetrofitManager
import com.halo.assistant.HaloApp
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import okhttp3.ResponseBody
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import retrofit2.HttpException

class ArticleDraftFragment : ListFragment<ArticleDraftEntity, NormalListViewModel<ArticleDraftEntity>>() {
    private val mApi = RetrofitManager.getInstance().api
    private var mAdapter: ArticleDraftAdapter? = null
    private var mArticleId: String? = null
    private var mOnlyCreateDraft = false

    override fun provideListAdapter(): ArticleDraftAdapter {
        if (mAdapter == null) {
            mAdapter = ArticleDraftAdapter(requireContext(), deleteCallback = { deleteDraft(it) }, selectCallback = {
                if (activity is CommunityDraftWrapperActivity) {
                    checkStoragePermissionBeforeAction {
                        /*if (it.articleId.isEmpty()) {
                            startActivity(ArticleEditActivity.getDraftIntent(requireContext(), it))
                        } else {
                            val detailEntity = ArticleDetailEntity(
                                    id = it.articleId,
                                    title = it.title,
                                    community = it.community)
                            startActivity(ArticleEditActivity.getPatchIntent(requireContext(), detailEntity, it, true))
                        }*/
                        startActivity(ArticleEditActivity.getDraftIntent(requireContext(), it))
                    }
                } else if (activity != null) {
                    checkStoragePermissionBeforeAction {
                        val intent = Intent()
                        intent.putExtra(ArticleDraftEntity::class.java.simpleName, it)
                        activity?.setResult(Activity.RESULT_OK, intent)
                        activity?.finish()
                    }
                }
            })
        }
        return mAdapter!!
    }

    override fun provideDataObservable(page: Int): Observable<MutableList<ArticleDraftEntity>> {
        return if (mArticleId.isNullOrEmpty() && mOnlyCreateDraft) {
            mApi.getArticleDrafts(UserManager.getInstance().userId, page)
        } else {
            mApi.getArticleDrafts(
                UserManager.getInstance().userId,
                UrlFilterUtils.getFilterQuery("article_id", mArticleId),
                page
            )
        }
    }

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

    override fun onCreate(savedInstanceState: Bundle?) {
        mArticleId = arguments?.getString(EntranceConsts.KEY_COMMUNITY_ARTICLE_ID)
        mOnlyCreateDraft = arguments?.getBoolean(EntranceConsts.KEY_ONLY_CREATE_DRAFT) ?: false
        super.onCreate(savedInstanceState)
        if (activity is ArticleDraftActivity) {
            setNavigationTitle("帖子草稿")
        }
    }

    override fun getItemDecoration(): RecyclerView.ItemDecoration {
        val insetDivider = ContextCompat.getDrawable(requireContext(), R.drawable.divider_item_line_space_16)
        val itemDecoration = CustomDividerItemDecoration(requireContext(), notDecorateTheLastItem = true)
        itemDecoration.setDrawable(insetDivider!!)
        return itemDecoration
    }

    private fun deleteDraft(entity: ArticleDraftEntity) {
        mApi.deleteArticleDrafts(UserManager.getInstance().userId, entity.id)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Response<ResponseBody>() {
                override fun onResponse(response: ResponseBody?) {
                    val index = mAdapter?.entityList?.indexOf(entity) ?: -1
                    if (index >= 0) {
                        mAdapter?.entityList?.remove(entity)
                        if (mAdapter?.entityList.isNullOrEmpty()) {
                            mListViewModel.load(LoadType.REFRESH)
                        } else {
                            mAdapter?.notifyItemRemoved(index)
                        }
                    }
                }

                override fun onFailure(e: HttpException?) {
                    toast(R.string.post_failure_hint)
                }
            })
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEventMainThread(reuse: EBReuse) {
        if (ArticleEditActivity.ARTICLE_DRAFT_CHANGE_TAG == reuse.type) {
            mBaseHandler.postDelayed({ mListViewModel.load(LoadType.REFRESH) }, 100)
        }
    }

    override fun onDarkModeChanged() {
        super.onDarkModeChanged()
        if ((mListRv?.itemDecorationCount ?: 0) > 0) {
            mListRv?.removeItemDecorationAt(0)
            mListRv?.addItemDecoration(itemDecoration)
        }
    }
}
