package com.ydl.ydlcommon.actions.imagepicker

import android.app.Activity
import android.content.Intent
import com.lzy.imagepicker.ImagePicker
import com.lzy.imagepicker.bean.ImageItem
import com.lzy.imagepicker.ui.ImageGridActivity
import com.ydl.ydlcommon.base.BaseActivity
import com.ydl.ydlcommon.utils.remind.ToastHelper


/**
 * author : Zhangwenchao
 * e-mail : zhangwch@yidianling.com
 * time   : 2018/05/07
 */
internal class ImagePickerActivity: BaseActivity() {

    companion object {
        private const val REQUEST_CODE = 0X00

        private var callback: PickerCallback? = null

        private const val OPEN_CAMERA = "open_camera"

        fun start(activity: Activity, openCamera: Boolean, callback: PickerCallback) {
            val intent = Intent(activity, ImagePickerActivity::class.java)
            intent.putExtra(OPEN_CAMERA, openCamera)
            activity.startActivityForResult(intent,
                REQUEST_CODE
            )
            Companion.callback = callback
        }
    }

    private var openCamera = false // 是否是直接打开相机

    override fun layoutResId(): Int {
        return 0
    }

    override fun initDataAndEvent() {
        openCamera = intent.getBooleanExtra(OPEN_CAMERA, false)
        val intent = Intent(this, ImageGridActivity::class.java)
        intent.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS, openCamera)
        startActivityForResult(intent,
            REQUEST_CODE
        )
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            if (data != null && requestCode == REQUEST_CODE) {
                val images = data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS) as ArrayList<ImageItem>
                callback?.onSuccess(images)
            } else {
                callback?.onFail()
                ToastHelper.show("没有数据")
            }
            finish()
        }
    }

    override fun onRestart() {
        super.onRestart()
        finish()
    }


}