package cn.muchinfo.rma.view.autoWidget.photopicter;

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.widget.TextView
import android.widget.Toast
import android.widget.Toast.LENGTH_LONG
import androidx.appcompat.app.AppCompatActivity
import cn.muchinfo.rma.R
import cn.muchinfo.rma.view.autoWidget.commonLeftButton
import cn.muchinfo.rma.view.autoWidget.commonTextButton
import cn.muchinfo.rma.view.autoWidget.commonTitle
import cn.muchinfo.rma.view.autoWidget.photopicter.PhotoPicker.*
import cn.muchinfo.rma.view.autoWidget.photopicter.event.OnItemCheckListener
import cn.muchinfo.rma.view.autoWidget.photopicter.fragment.ImagePagerFragment
import cn.muchinfo.rma.view.autoWidget.photopicter.fragment.PhotoPickerFragment
import cn.muchinfo.rma.view.autoWidget.topBar
import org.jetbrains.anko.*
import java.util.*

class PhotoPickerActivity : AppCompatActivity() {

    private var pickerFragment: PhotoPickerFragment? = null
    private var imagePagerFragment: ImagePagerFragment? = null
    private lateinit var menuText: TextView

    private var maxCount = DEFAULT_MAX_COUNT

    /** to prevent multiple calls to inflate menu  */
    private var menuIsInflated = false

    var isShowGif = false
    private var originalPhotos: ArrayList<String>? = null

    val activity: PhotoPickerActivity
        get() = this


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

        val showCamera = intent.getBooleanExtra(EXTRA_SHOW_CAMERA, true)
        val showGif = intent.getBooleanExtra(EXTRA_SHOW_GIF, false)
        val previewEnabled = intent.getBooleanExtra(EXTRA_PREVIEW_ENABLED, true)

        isShowGif = showGif

        verticalLayout {
            topBar {
                commonLeftButton()
                commonTitle {
                    textResource = R.string.__picker_title
                }
                commonTextButton(resources.getString(R.string.__picker_done)) {
                    val intent = Intent()
                    var selectedPhotos: ArrayList<String>? = null
                    if (pickerFragment != null) {
                        selectedPhotos = pickerFragment!!.photoGridAdapter.selectedPhotoPaths
                    }
                    //当在列表没有选择图片，又在详情界面时默认选择当前图片
                    if (selectedPhotos!!.size <= 0) {
                        if (imagePagerFragment != null && imagePagerFragment!!.isResumed) {
                            // 预览界面
                            selectedPhotos = imagePagerFragment!!.currentPath
                        }
                    }
                    if (selectedPhotos != null && selectedPhotos.size > 0) {
                        intent.putStringArrayListExtra(KEY_SELECTED_PHOTOS, selectedPhotos)
                        setResult(Activity.RESULT_OK, intent)
                        finish()
                    }
                }
                menuText = find(R.id.top_bar_right_text)
                if (originalPhotos != null && originalPhotos!!.size > 0) {
                    menuText.isEnabled = true
                    menuText.text = resources.getString(R.string.__picker_done_with_count, originalPhotos!!.size, maxCount)
                } else {
                    menuText.isEnabled = false
                }
            }
            frameLayout { id = R.id.container }.lparams(matchParent, 0, 1f)
        }

        maxCount = intent.getIntExtra(EXTRA_MAX_COUNT, DEFAULT_MAX_COUNT)
        val columnNumber = intent.getIntExtra(EXTRA_GRID_COLUMN, DEFAULT_COLUMN_NUMBER)
        originalPhotos = intent.getStringArrayListExtra(EXTRA_ORIGINAL_PHOTOS)

        pickerFragment = supportFragmentManager.findFragmentByTag("tag") as? PhotoPickerFragment
        if (pickerFragment == null) {
            pickerFragment = PhotoPickerFragment
                    .newInstance(showCamera, showGif, previewEnabled, columnNumber, maxCount, originalPhotos)
            supportFragmentManager
                    .beginTransaction()
                    .replace(R.id.container, pickerFragment!!, "tag")
                    .commit()
            supportFragmentManager.executePendingTransactions()
        }

        pickerFragment!!.photoGridAdapter.setOnItemCheckListener(OnItemCheckListener { _, photo, selectedItemCount ->
            menuText.isEnabled = selectedItemCount > 0

            if (maxCount <= 1) {
                val photos = pickerFragment!!.photoGridAdapter.selectedPhotos
                if (!photos.contains(photo.path)) {
                    photos.clear()
                    pickerFragment!!.photoGridAdapter.notifyDataSetChanged()
                }
                return@OnItemCheckListener true
            }

            if (selectedItemCount > maxCount) {
                Toast.makeText(activity, resources.getString(R.string.__picker_over_max_count_tips, maxCount),
                        LENGTH_LONG).show()
                return@OnItemCheckListener false
            }
            if (maxCount > 1) {
                menuText.text = resources.getString(R.string.__picker_done_with_count, selectedItemCount, maxCount)
            } else {
                menuText.text = resources.getString(R.string.__picker_done)
            }
            true
        })

    }

    //刷新右上角按钮文案
    fun updateTitleDoneItem() {
        if (menuIsInflated) {
            if (pickerFragment != null && pickerFragment!!.isResumed) {
                val photos = pickerFragment!!.photoGridAdapter.selectedPhotos
                val size = photos?.size ?: 0
                menuText.isEnabled = size > 0
                if (maxCount > 1) {
                    menuText.text = resources.getString(R.string.__picker_done_with_count, size, maxCount)
                } else {
                    menuText.text = resources.getString(R.string.__picker_done)
                }

            } else if (imagePagerFragment != null && imagePagerFragment!!.isResumed) {
                //预览界面 完成总是可点的，没选就把默认当前图片
                menuText.isEnabled = true
            }

        }
    }

    /**
     * Overriding this method allows us to run our exit animation first, then exiting
     * the activity when it complete.
     */
    override fun onBackPressed() {
        if (imagePagerFragment != null && imagePagerFragment!!.isVisible) {
            if (supportFragmentManager.backStackEntryCount > 0) {
                supportFragmentManager.popBackStack()
            }
        } else {
            super.onBackPressed()
        }
    }


    fun addImagePagerFragment(imagePagerFragment: ImagePagerFragment) {
        this.imagePagerFragment = imagePagerFragment
        supportFragmentManager
                .beginTransaction()
                .replace(R.id.container, this.imagePagerFragment!!)
                .addToBackStack(null)
                .commit()
    }
}
