package com.ydl.ydlcommon.actions.imagepicker

import android.content.Intent
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import com.lzy.imagepicker.ImagePicker
import com.lzy.imagepicker.bean.ImageItem
import com.lzy.imagepicker.ui.ImageGridActivity
import com.ydl.ydlcommon.base.BaseFragment
import com.ydl.ydlcommon.utils.remind.ToastHelper

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

    companion object {
        private const val REQUEST_CODE = 0X00

        private const val OPEN_CAMERA = "open_camera"

        private const val PICKER: String = "picker"

        fun start(activity: AppCompatActivity, openCamera: Boolean, callback: PickerCallback) {
            val fragment = ImagePickerFragment()
            fragment.pickerCallback = callback
            val args = Bundle()
            args.putBoolean(OPEN_CAMERA, openCamera)
            fragment.arguments = args
            activity.supportFragmentManager.beginTransaction()
                    .add(fragment, PICKER)
                    .commitAllowingStateLoss()
        }
    }

    private var pickerCallback: PickerCallback? = null

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

    override fun layoutResId(): Int {
        return 0
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        openCamera = arguments.getBoolean(OPEN_CAMERA, false)
        val intent = Intent(activity, ImageGridActivity::class.java)
        startActivityForResult(intent,
            REQUEST_CODE
        )
    }

    override fun initDataAndEvent() {

    }

    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>
                pickerCallback?.onSuccess(images)
            } else {
                pickerCallback?.onFail()
                ToastHelper.show("没有数据")
            }
        }
    }

    override fun initDataAndEventLazy() {

    }
}