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

import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.media.MediaScannerConnection
import android.net.Uri
import android.os.Build
import android.os.Environment
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import cn.muchinfo.rma.R
import cn.muchinfo.rma.view.autoWidget.toArrayList
import com.tbruyelle.rxpermissions2.RxPermissions
import mtp.polymer.com.autowidget.dialog.createWarningDialog

import java.io.File
import java.io.FileNotFoundException
import java.io.FileOutputStream
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.*
import kotlin.collections.ArrayList

class PhotoUtils {


    fun saveBitmap(context: Context,bitmap : Bitmap,onSavePath : ((String) -> Unit)){
        val root = Environment.getExternalStorageDirectory().absolutePath
        val dirName = context.packageName

        val appDir = File(root, dirName)
        if (!appDir.exists()) {
            appDir.mkdirs()
        }

        //文件名为时间
        val timeStamp = System.currentTimeMillis()
        val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
        val sd = sdf.format(Date(timeStamp))
        val fileName = "$sd.jpg"

        //获取文件
        val file = File(appDir, fileName)
        var fos: FileOutputStream? = null
        try {
            fos = FileOutputStream(file)
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos)
            fos.flush()
            //通知系统相册刷新
            context.sendBroadcast(Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                    Uri.fromFile(File(file.path))))
            onSavePath.invoke(file.path)
        } catch (e: FileNotFoundException) {
            e.printStackTrace()
        } catch (e: IOException) {
            e.printStackTrace()
        } finally {
            try {
                fos?.close()
            } catch (e: IOException) {
                e.printStackTrace()
            }

        }
    }

    /**
     * 预览图片
     */
    fun showImageViewer(activity: AppCompatActivity, currentImage: Int, images: List<String>) {

        PhotoPreview.builder()
                .setPhotos(images.toArrayList())
                .setCurrentItem(currentImage)
                .setShowDeleteButton(false)
                .start(activity)
    }

    fun showPicker(activity: AppCompatActivity, imageCount: Int = 1, selectedList: List<String>? = null, onPickerAction: ((List<String>) -> Unit)){

        RxPermissions(activity).request(Manifest.permission.READ_EXTERNAL_STORAGE)
                .subscribe { granted ->
                    if (granted) {
                        startPickerActivity(activity, imageCount, selectedList, onPickerAction)
                    } else {
                        showPermissionError(activity)
                    }
                }

    }


    private fun startPickerActivity(activity: AppCompatActivity, imageCount: Int, selectedList: List<String>?, onPickerAction: ((List<String>) -> Unit)) {
        val validFragment = HolderFragment()
        activity.supportFragmentManager.beginTransaction().add(validFragment, HolderFragment.TAG_PICKER_FRAGMENT).commit()
        validFragment.onPickerAction = onPickerAction
        validFragment.onAttachAction = {
            PhotoPicker.builder()
                    .setSelected(ArrayList<String>().apply { selectedList?.let { addAll(it) } })
                    .setPhotoCount(imageCount)
                    .setShowCamera(true)
                    .setPreviewEnabled(false)
                    .start(activity, validFragment)
        }
    }


    private fun showPermissionError(activity: AppCompatActivity) {
        activity.createWarningDialog {
            setTitle(activity.resources.getString(R.string.hint))
            setMessage(activity.resources.getString(R.string.no_storage_permission))
            addAction(activity.resources.getString(R.string.cancle)) { dialog, _ -> dialog.dismiss() }
            addAction(activity.resources.getString(R.string.go_setting)) { dialog, _ ->
                dialog.dismiss()
//                AppUtils.getAppDetailsSettings()
            }
        }.show()
    }
}


class HolderFragment : Fragment() {

    companion object {
        const val TAG_PICKER_FRAGMENT = "TAG_PICKER_FRAGMENT"
    }

    var onPickerAction: ((List<String>) -> Unit)? = null

    var onAttachAction: (() -> Unit)? = null

    override fun onAttach(context: Context) {
        super.onAttach(context)
        onAttachAction?.invoke()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == PhotoPicker.REQUEST_CODE) {
            if (resultCode == Activity.RESULT_OK) {
                val photos = data?.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS)
                onPickerAction?.invoke(photos ?: emptyList())
            }
            activity?.supportFragmentManager?.beginTransaction()?.remove(this)?.commit()
            onPickerAction = null
            onAttachAction = null
        }
    }
}
