package com.kdanmobile.reader.screen.reader.mediabox.signature

import android.content.Context
import android.content.Intent
import android.support.constraint.ConstraintLayout
import android.support.v7.widget.GridLayoutManager
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import com.kdanmobile.reader.Config
import com.kdanmobile.reader.R
import com.kdanmobile.reader.screen.data.SignatureAttribute
import com.kdanmobile.reader.screen.reader.mediabox.common.MediaBoxHeader
import com.kdanmobile.reader.screen.signature.SignatureActivity
import com.kdanmobile.reader.utils.DensityUtil
import kotlinx.android.synthetic.main.view_media_box_tab_signature.view.*
import java.io.File
import java.util.*


class SignatureTabView : ConstraintLayout {

    var onMediaBoxHeaderClickListener: MediaBoxHeader.OnTitleButtonClickListener? = null

    private lateinit var signaturePaths: ArrayList<String>
    private lateinit var selectedSignaturePath: String

    constructor(context: Context) : super(context) {
        initView()
    }

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
        initView()
    }

    constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle) {
        initView()
    }

    private fun initView() {
        LayoutInflater.from(context).inflate(R.layout.view_media_box_tab_signature, this)

        updateSignaturePaths()
        updateSignatureMessage()

        recyclerView_signature.layoutManager = GridLayoutManager(context, resources.getInteger(R.integer.mediaBox_signature_columnCount))
        val adapter = SignatureAdapter(context, signaturePaths)
        adapter.setOnSignatureClickListener(object : OnSignatureClickListener {
            override fun onSignatureClick(path: String) {
                selectedSignaturePath = path
                onMediaBoxHeaderClickListener?.onTitleButtonClick()
            }
        })
        adapter.setOnSignatureRemoveListener(object : OnSignatureRemoveListener {
            override fun onSignatureRemove(path: String) {
                val position = signaturePaths.indexOf(path)

                val layoutManager = recyclerView_signature.layoutManager as GridLayoutManager
                val updateRow = (position - 1) / layoutManager.spanCount
                val positionStart = updateRow * layoutManager.spanCount
                adapter.notifyItemRangeChanged(positionStart, adapter.itemCount - positionStart)

                signaturePaths.removeAt(position)
                adapter.notifyItemRemoved(position)
                File(path).delete()
                updateSignatureMessage()
            }
        })
        btn_add_signature.setOnClickListener {
            SignatureActivity.signatureAddNotifyManager = object : OnSignatureAddListener {
                override fun onSignatureAdd(path: String) {
                    signaturePaths.add(0, path)
                    adapter.notifyDataSetChanged()
                    recyclerView_signature.smoothScrollToPosition(0)
                    updateSignatureMessage()
                }
            }
            context.startActivity(Intent(context, SignatureActivity::class.java))
        }
        recyclerView_signature.adapter = adapter
        recyclerView_signature.setHasFixedSize(true)

        recyclerView_signature.addItemDecoration(SignatureRecyclerViewItemDecoration(DensityUtil.dp2px(context, 8f), DensityUtil.dp2px(context, 88f)))
    }

    fun getSignatureAttribute() : SignatureAttribute {
        return SignatureAttribute(selectedSignaturePath)
    }

    private fun updateSignaturePaths() {
        val path = Config.getSignatureDirectoryPath(context)
        val array = File(path).list { _, name -> name.toLowerCase(Locale.US).endsWith(".png") }
        signaturePaths = when (null != array) {
            true -> array.toCollection(ArrayList())
            false -> arrayListOf()
        }
        signaturePaths.sortByDescending { it }
        for (i in 0 until signaturePaths.size) {
            signaturePaths[i] = "$path${File.separator}${signaturePaths[i]}"
        }
    }

    private fun updateSignatureMessage() {
        tv_noSignature.visibility = if (signaturePaths.size == 0) View.VISIBLE else View.INVISIBLE
        recyclerView_signature.visibility = if (signaturePaths.size == 0) View.INVISIBLE else View.VISIBLE
    }
}