package com.gh.gamecenter.qa.editor

import android.content.Context
import android.content.Intent
import android.database.Cursor
import android.os.Bundle
import android.view.View
import android.widget.AdapterView
import android.widget.ImageView
import android.widget.PopupWindow
import androidx.core.content.ContextCompat
import com.gh.gamecenter.common.base.activity.ToolBarActivity
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.R
import com.gh.gamecenter.common.utils.updateStatusBarColor
import com.halo.assistant.HaloApp
import com.zhihu.matisse.Matisse
import com.zhihu.matisse.MimeType
import com.zhihu.matisse.internal.entity.Album
import com.zhihu.matisse.internal.entity.SelectionSpec
import com.zhihu.matisse.internal.model.AlbumCollection

class LocalMediaActivity : ToolBarActivity(), AlbumCollection.AlbumCallbacks {
    private var mLocalMediaFragment: LocalMediaFragment? = null
    private lateinit var mAlbumsSpinner: VideoAlbumsSpanner
    private lateinit var mAlbumsAdapter: VideoAlbumsAdapter
    private val mAlbumCollection = AlbumCollection()
    private var mIsFirstAlbumLoad = true
    private var mChooseType = ""

    override fun getLayoutId(): Int = R.layout.activity_video_tablayout_viewpager

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        updateStatusBarColor(R.color.background_white, R.color.background_white)
        mChooseType = intent.getStringExtra(EntranceConsts.KEY_TYPE) ?: ""
        if (mChooseType == ChooseType.VIDEO.value) {
            setNavigationTitle("本地视频")
        } else {
            setNavigationTitle("本地图片")
        }
        mLocalMediaFragment = LocalMediaFragment().apply { arguments = intent.extras }
        supportFragmentManager.beginTransaction()
            .replace(R.id.container, mLocalMediaFragment!!, LocalMediaFragment::class.java.name)
            .commitAllowingStateLoss()
        initAlbumsSpinner()
        mTitleTv.setOnClickListener {
            mAlbumsSpinner.show(findViewById<View>(R.id.container).height)
            setPhotoNavigationTitle(true)
        }
    }

    private fun initAlbumsSpinner() {
        mAlbumsSpinner = VideoAlbumsSpanner(this)
        mAlbumsAdapter = VideoAlbumsAdapter(this)

        mAlbumsSpinner.setPopupAnchorView(findViewById(R.id.normal_toolbar))
        mAlbumsSpinner.setAdapter(mAlbumsAdapter)
        mAlbumsSpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onNothingSelected(parent: AdapterView<*>?) {

            }

            override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
                mAlbumCollection.setStateCurrentSelection(position)
                mAlbumsAdapter.cursor.moveToPosition(position)
                val album = Album.valueOf(mAlbumsAdapter.cursor)
                if (album.isAll && SelectionSpec.getInstance().capture) {
                    album.addCaptureCount()
                }
                if (mLocalMediaFragment?.isAdded == true) {
                    mLocalMediaFragment?.loadVideos(album)
                }
            }
        }

        mAlbumsSpinner.setDismissListener(PopupWindow.OnDismissListener {
            setPhotoNavigationTitle(false)
        })
        //必须加这行代码，[SelectionSpec]是单例模式，下次使用必须先更新MimeType
        val mimeType = if (mChooseType == ChooseType.VIDEO.value) {
            MimeType.ofVideo()
        } else {
            MimeType.ofImage()
        }
        val maxChooseCount = intent.getIntExtra(EntranceConsts.KEY_CHOOSE_MAX_COUNT, 1)
        Matisse.from(this).choose(mimeType).showSingleMediaType(true).maxSelectable(maxChooseCount)
        mAlbumCollection.onCreate(this, this)
        mAlbumCollection.loadAlbums()
    }

    override fun onAlbumLoad(cursor: Cursor?) {
        if (mIsFirstAlbumLoad) {
            mIsFirstAlbumLoad = false
            mAlbumsAdapter.swapCursor(cursor)
            mBaseHandler.post {
                cursor?.moveToPosition(mAlbumCollection.currentSelection)
                val album = Album.valueOf(cursor)
                if (album.isAll && SelectionSpec.getInstance().capture) {
                    album.addCaptureCount()
                }
                if (mLocalMediaFragment?.isAdded == true) {
                    mLocalMediaFragment?.loadVideos(album)
                }
            }
        }

    }

    override fun onAlbumReset() {

    }


    private fun setPhotoNavigationTitle(up: Boolean) {
        val drawable = ContextCompat.getDrawable(
            HaloApp.getInstance().application,
            if (up) R.drawable.ic_video_arrow_up else R.drawable.ic_video_arrow_down
        )
        val arrowIv = findViewById<ImageView>(R.id.arrowIv)
        arrowIv?.setImageDrawable(drawable)
    }

    override fun isAutoResetViewBackgroundEnabled(): Boolean = true

    override fun onDarkModeChanged() {
        super.onDarkModeChanged()
        updateStatusBarColor(R.color.background_white, R.color.background_white)
    }

    companion object {
        fun getIntent(context: Context, chooseType: ChooseType, maxChooseCount: Int = 1, entrance: String): Intent {
            return Intent(context, LocalMediaActivity::class.java).apply {
                putExtra(EntranceConsts.KEY_TYPE, chooseType.value)
                putExtra(EntranceConsts.KEY_CHOOSE_MAX_COUNT, maxChooseCount)
                putExtra(EntranceConsts.KEY_ENTRANCE, entrance)
            }
        }
    }

    enum class ChooseType(val value: String) {
        VIDEO("video"),
        IMAGE("image")
    }
}