package jp.beaa.okaeri.activity

import android.app.Activity
import android.app.ProgressDialog
import android.content.Context
import android.content.Intent
import android.databinding.DataBindingUtil
import android.graphics.Bitmap
import android.graphics.Matrix
import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.support.v7.app.AppCompatActivity
import com.isseiaoki.simplecropview.CropImageView
import com.isseiaoki.simplecropview.callback.CropCallback
import com.isseiaoki.simplecropview.callback.LoadCallback
import jp.beaa.okaeri.R
import jp.beaa.okaeri.databinding.ActivityImageCropBinding

/**
 * Created by satoumasanori on 2017/09/24.
 */
class ImageCropActivity: AppCompatActivity() {
    companion object {
        private val KEY_URI = "KEY_URI"
        private val KEY_REQUEST_CODE = "KEY_REQUEST_CODE"
        fun start(activity: Activity, uri: Uri, requestCode: Int) {
            val intent = Intent(activity, ImageCropActivity::class.java)
            intent.putExtra(KEY_URI, uri.toString())
            intent.putExtra(KEY_REQUEST_CODE, requestCode)
            activity.startActivityForResult(intent, requestCode)
        }
    }

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

        if (!intent.hasExtra(KEY_URI)) finish()
        val uri = Uri.parse(intent.getStringExtra(KEY_URI))
        val requestCode = intent.getIntExtra(KEY_REQUEST_CODE, 0)

        val binding = DataBindingUtil.setContentView<ActivityImageCropBinding>(this, R.layout.activity_image_crop)
        binding.cropImageView.setCropMode(CropImageView.CropMode.RATIO_16_9)
        binding.cropImageView.load(uri).execute(object : LoadCallback {
            override fun onSuccess() {}

            override fun onError(e: Throwable?) {
                e!!.printStackTrace()
            }

        })

        binding.cropButton.setOnClickListener {
            binding.cropImageView.crop(uri).execute(object : CropCallback {
                override fun onSuccess(cropped: Bitmap) {
                    val progressDialog = ProgressDialog(this@ImageCropActivity)
                    progressDialog.setMessage("画像保存中...")
                    progressDialog.show()
                    val handler = Handler()
                    Thread(Runnable {
                        val size = resources.getDimensionPixelSize(R.dimen.cropHeight) * 2
                        val resizeBitmap = resize(cropped, size, size)
                        val fileName = "okaeriImage"
                        val out = openFileOutput(fileName, Context.MODE_PRIVATE)
                        resizeBitmap.compress(Bitmap.CompressFormat.PNG, 100, out)

                        handler.post {
                            val intent = Intent()
                            intent.data = Uri.parse(filesDir.absolutePath + "/" + fileName)
                            setResult(requestCode, intent)
                            finish()
                            progressDialog.dismiss()
                        }
                    }).start()
                }

                override fun onError(e: Throwable?) {
                    e!!.printStackTrace()
                }
            })
        }
    }

    /**
     * 画像リサイズ
     * @param bitmap 変換対象ビットマップ
     * @param newWidth 変換サイズ横
     * @param newHeight 変換サイズ縦
     * @return 変換後Bitmap
     */
    fun resize(bitmap: Bitmap, newWidth: Int, newHeight: Int): Bitmap {

        val oldWidth = bitmap.width
        val oldHeight = bitmap.height

        if (oldWidth < newWidth && oldHeight < newHeight) {
            // 縦も横も指定サイズより小さい場合は何もしない
            return bitmap
        }

        val scaleWidth = newWidth.toFloat() / oldWidth
        val scaleHeight = newHeight.toFloat() / oldHeight
        val scaleFactor = Math.min(scaleWidth, scaleHeight)

        val scale = Matrix()
        scale.postScale(scaleFactor, scaleFactor)

        val resizeBitmap = Bitmap.createBitmap(bitmap, 0, 0, oldWidth, oldHeight, scale, false)
        bitmap.recycle()

        return resizeBitmap

    }
}