package com.kdanmobile.reader.copyfile

import android.arch.lifecycle.Observer
import android.content.Intent
import android.os.Bundle
import com.kdanmobile.base.KdanBaseActivity
import com.kdanmobile.reader.R
import com.kdanmobile.reader.thumb.FileUtil
import kotlinx.android.synthetic.main.activity_copy_file.*
import org.koin.android.viewmodel.ext.android.viewModel
import org.koin.core.parameter.parametersOf
import java.io.File

abstract class CopyFileActivity : KdanBaseActivity() {

    abstract fun getKdanPdfReaderFolder(): File
    abstract fun provideReaderActivityIntent(filePath: String?): Intent
    open fun hasPermissionToAccessExternalStorage(): Boolean = true

    companion object {
        const val KEY_FILE_ABSOLUTE_PATH = "file_absolute_path"
        const val KEY_SHOULD_COPY_FILE = "should_copy_file"
    }

    private val viewModel: CopyFileViewModel by viewModel {
        val kdanPdfReaderFolder = getKdanPdfReaderFolder()
        FileUtil.init(kdanPdfReaderFolder)
        val info = CopyFileInfoFactory().createInfo(this, intent, kdanPdfReaderFolder)
        parametersOf(applicationContext, info)
    }

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

        viewModel.copyProgressLiveData.observe(this, Observer(this::onCopyProgressUpdate))
        viewModel.eventLiveData.observe(this, Observer(this::onEvent))
    }

    private fun onCopyProgressUpdate(progress: Int?) {
        progress?.also {
            progressBar.progress = it
            tvProgressPercent.text = "$it%"
        }
    }

    private fun onEvent(event: CopyFileViewModel.Event?) {
        if (null == event) return
        when (event) {
            is CopyFileViewModel.Event.Success -> {
                startReaderActivity(event.filePath)
            }
            is CopyFileViewModel.Event.Failed -> {
                event.e.printStackTrace()
                showFileCannotOpenDialog(getString(R.string.cannot_open_file_Path, event.filePath))
            }
        }
        viewModel.onEventConsumed(event)
    }

    private fun showFileCannotOpenDialog(title: String) {
        if (!hasPermissionToAccessExternalStorage()) return
        val fileCannotOpenDialog = FileCannotOpenDialogFragment()
        fileCannotOpenDialog.arguments = Bundle().also {
            it.putString(FileCannotOpenDialogFragment.KEY_DIALOG_TITLE, title)
        }
        fileCannotOpenDialog.isCancelable = false
        fileCannotOpenDialog.show(supportFragmentManager, fileCannotOpenDialog.tag)
    }

    private fun startReaderActivity(filePath: String?) {
        startActivity(provideReaderActivityIntent(filePath))
        overridePendingTransition(0, 0)
        finish()
    }

    protected fun copyFile() {
        viewModel.copyFile(applicationContext)
    }
}