package com.kdanmobile.reader.screen.signature

import android.graphics.Bitmap
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.support.v7.app.AppCompatActivity
import android.view.MenuItem
import android.view.View
import android.widget.SeekBar
import com.kdanmobile.reader.Config
import com.kdanmobile.reader.R
import com.kdanmobile.reader.screen.reader.mediabox.signature.OnSignatureAddListener
import com.kdanmobile.reader.screen.view.ColorSelectView
import kotlinx.android.synthetic.main.activity_view_signature_create.*
import java.io.File
import java.io.FileOutputStream
import java.io.IOException

class SignatureActivity : AppCompatActivity() {

    companion object {
        var signatureAddNotifyManager: OnSignatureAddListener? = null
    }

    private var onSignatureAddListener: OnSignatureAddListener? = null
    private var hasNoSignature = true
        set(value) {
            field = value
            when (field) {
                true -> {
                    tv_writeHere.visibility = View.VISIBLE
                    btn_save_signature.setTextColor(ContextCompat.getColor(baseContext, android.R.color.darker_gray))
                    btn_save_signature.isClickable = false
                }
                false -> {
                    tv_writeHere.visibility = View.INVISIBLE
                    btn_save_signature.setTextColor(ContextCompat.getColor(baseContext, android.R.color.white))
                    btn_save_signature.isClickable = true
                }
            }
        }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_view_signature_create)

        onSignatureAddListener = signatureAddNotifyManager
        signatureAddNotifyManager = null

        setupToolbar()

        colorChooser_signature.onColorSelectedListener = object : ColorSelectView.OnColorSelectedListener {
            override fun onColorSelected(color: Int) {
                drawView.paintColor = color
            }
        }
        drawView.paintColor = colorChooser_signature.getSelectedColor()

        seekBar_signature.onSeekBarChangeListener = object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                drawView.strokeWidth = seekBar_signature.currentValue.toFloat()
            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {}

            override fun onStopTrackingTouch(seekBar: SeekBar?) {
                drawView.strokeWidth = seekBar_signature.currentValue.toFloat()
            }
        }
        drawView.strokeWidth = seekBar_signature.currentValue.toFloat()

        btn_save_signature.setOnClickListener {
            if (!hasNoSignature) {
                val bitmap = getCropBitmap(drawView.getBitmap())
                val path = Config.getSignatureDirectoryPath(baseContext)
                val filename = "Signature${System.currentTimeMillis()}.png"
                saveBitmap(bitmap, path, filename)

                onSignatureAddListener?.onSignatureAdd("$path${File.separator}$filename")
                finish()
            }
        }

        btn_clear_signature.setOnClickListener {
            drawView.clear()
        }

        drawView.onSignatureDrawListener = object : SignatureDrawView.OnSignatureDrawListener {
            override fun onClearSignature() {
                hasNoSignature = true
            }

            override fun onStartSignature() {
                hasNoSignature = false
            }
        }
        hasNoSignature = true
    }

    private fun getCropBitmap(bitmap: Bitmap) : Bitmap {
        val argb = IntArray(bitmap.width * bitmap.height)
        bitmap.getPixels(argb, 0, bitmap.width, 0, 0, bitmap.width, bitmap.height)
        var minX = bitmap.width
        var maxX = 0
        var minY = bitmap.height
        var maxY = 0
        var index = 0
        for (y in 0 until bitmap.height) {
            for (x in 0 until bitmap.width) {
                val alpha = (argb[index] shr 24) and 0xff
                if (alpha > 10) {
                    minX = Math.min(x, minX)
                    maxX = Math.max(x, maxX)
                    minY = Math.min(y, minY)
                    maxY = Math.max(y, maxY)
                }
                index++
            }
        }

        return Bitmap.createBitmap(bitmap, minX, minY, maxX - minX + 1, maxY - minY + 1)
    }

    private fun saveBitmap(bitmap: Bitmap, path: String, filename: String) {
        val dir = File(path)
        if (!dir.exists() || !dir.isDirectory) {
            dir.mkdirs()
        }
        try {
            val fileOutputStream = FileOutputStream("$path${File.separator}$filename")
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream)
            fileOutputStream.close()
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }

    private fun setupToolbar() {
        setSupportActionBar(toolbar_signature)
        supportActionBar?.setHomeAsUpIndicator(R.drawable.ic_close)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
    }

    override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        when (item?.itemId) {
            android.R.id.home -> finish()
        }
        return super.onOptionsItemSelected(item)
    }
}
