package com.gh.gamecenter.amway.search

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import com.gh.gamecenter.DisplayType
import com.gh.gamecenter.SearchActivity
import com.gh.gamecenter.SearchType
import com.gh.gamecenter.common.utils.viewModelProvider
import com.gh.gamecenter.db.ISearchHistoryDao
import com.gh.gamecenter.search.SearchDefaultFragment

class AmwaySearchActivity : SearchActivity() {

    private lateinit var mViewModel: AmwaySearchViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        mViewModel = viewModelProvider()
    }

    override fun provideDao(): ISearchHistoryDao = AmwaySearchDao()

    override fun handleAutoSearch(key: String?) {
        mSearchKey = key
        updateDisplayType(DisplayType.GAME_DIGEST)
        mViewModel.getSearchResult(mSearchKey!!)
    }

    override fun handleHistorySearch(key: String?) {
        mSearchKey = key
        searchEt.setText(key)
        searchEt.setSelection(searchEt.text.length)
        mViewModel.getSearchResult(mSearchKey!!)
        updateDisplayType(DisplayType.GAME_DETAIL)
    }

    private fun handleOtherSearch() {
        val newSearchKey = searchEt.text.toString().trim { it <= ' ' }
        if (newSearchKey != mSearchKey || mDisplayType != DisplayType.GAME_DETAIL) {
            mSearchKey = newSearchKey
            if (!TextUtils.isEmpty(mSearchKey)) {
                mViewModel.getSearchResult(mSearchKey!!)
                mDao.add(mSearchKey!!)
                updateDisplayType(DisplayType.GAME_DETAIL)
            } else {
                toast("请先输入游戏名再搜索~")
            }
        }
    }

    override fun search(type: SearchType, key: String?) {
        mSearchType = type
        mIsAutoSearchDisabled = true
        when (type) {
            SearchType.AUTO -> handleAutoSearch(key)
            SearchType.HISTORY -> handleHistorySearch(key)
            else -> handleOtherSearch()
        }
        mIsAutoSearchDisabled = false
    }

    override fun updateDisplayType(type: DisplayType) {
        val transaction = when (type) {
            DisplayType.DEFAULT -> showFragment(
                SearchDefaultFragment::class.java.name,
                { AmwaySearchDefaultFragment() }
            )

            else -> showFragment(
                AmwaySearchListFragment::class.java.name,
                { AmwaySearchListFragment() }
            )
        }
        mDisplayType = type
        transaction.commitAllowingStateLoss()
    }

    companion object {
        fun getIntent(context: Context): Intent {
            val intent = Intent(context, AmwaySearchActivity::class.java)
            return intent
        }
    }

}