package com.yidianling.muse.utils

import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Environment
import android.provider.MediaStore
import android.view.View
import com.yidianling.common.tools.ToastUtil
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.lang.Exception
import java.text.SimpleDateFormat
import java.util.*
import kotlin.properties.Delegates

class ShareMeditationUtil {


    companion object {

        fun saveImageToLocal(view: View){
            val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.CHINA).format(Date())
            val fileName = "IMG_$timeStamp"
            val bitmap = saveViewBitmapToAlbum(view,fileName,true)
        }

        private fun saveViewBitmapToAlbum(view: View, name: String, isPrompt: Boolean):Bitmap?{
            view.isDrawingCacheEnabled = false
            view.isDrawingCacheEnabled = true
            view.measure(view.measuredWidth,view.measuredHeight)
            try {
                val bitmap = view.drawingCache
                return saveBitmapToAlbum(view.context,bitmap,name, isPrompt)
            }catch (e:Exception){

            }
            return null
        }

        private fun saveBitmapToAlbum(context: Context, bitmap: Bitmap, name:String, isPrompt:Boolean):Bitmap?{

            var fileName by Delegates.notNull<String>()

            val galleryPath = Environment.getExternalStorageDirectory().toString()+File.separator +
                    Environment.DIRECTORY_DCIM + File.separator + "Camera" + File.separator

            var file:File?=null
            var outStream:FileOutputStream?=null
            try {
                file = File(galleryPath, "$name.png")
                fileName = file.toString()
                outStream = FileOutputStream(fileName)
                bitmap.compress(Bitmap.CompressFormat.PNG,90,outStream)
            }catch (e:Exception){

            }finally {
                try {
                    outStream?.close()
                }catch (e:IOException){

                }
            }

            MediaStore.Images.Media.insertImage(context.contentResolver,bitmap,fileName,null)
            val intent = Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE)
            val uri = Uri.fromFile(file)
            intent.data = uri
            context.sendBroadcast(intent)
            if (isPrompt){
                ToastUtil.toastShort(if (bitmap!=null) "已保存" else "保存失败")
            }
            return bitmap
        }

    }

}