package com.base.pdfreaderallpdfreader.ui.search

import android.graphics.Color
import android.view.View
import android.view.inputmethod.EditorInfo
import androidx.activity.addCallback
import androidx.core.view.updatePadding
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import com.base.pdfreaderallpdfreader.base.BaseActivity
import com.base.pdfreaderallpdfreader.bean.DocumentBean
import com.base.pdfreaderallpdfreader.bean.DocumentBean.Companion.TYPE_PDF
import com.base.pdfreaderallpdfreader.databinding.ActivitySearchBinding
import com.base.pdfreaderallpdfreader.databinding.ItemTabDocumentBinding
import com.base.pdfreaderallpdfreader.ui.document.DocumentFragment.Companion.jumpOtherDocument
import com.base.pdfreaderallpdfreader.ui.main.DocumentAdapter
import com.base.pdfreaderallpdfreader.ui.pdf.PdfActivity
import com.base.pdfreaderallpdfreader.ui.view.DocumentDialog.showDocumentHomeMoreDialog
import com.base.pdfreaderallpdfreader.ui.view.DocumentHomeMoreCallBack
import com.base.pdfreaderallpdfreader.utils.BarUtils
import com.base.pdfreaderallpdfreader.utils.LogEx
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.io.File

class SearchActivity : BaseActivity<ActivitySearchBinding>(), DocumentHomeMoreCallBack {

    private val TAG = "SearchActivity"
    private lateinit var searchViewModel: SearchViewModel
    private var adapter: DocumentAdapter? = null

    override val binding: ActivitySearchBinding by lazy {
        ActivitySearchBinding.inflate(layoutInflater)
    }

    override fun initView() {
        BarUtils.setStatusBarLightMode(this, true)
        BarUtils.setStatusBarColor(this, Color.WHITE)
        binding.root.updatePadding(top = BarUtils.getStatusBarHeight())
        searchViewModel = ViewModelProvider(this)[SearchViewModel::class.java]

        adapter = DocumentAdapter()
        binding.rv.adapter = adapter
        adapter?.moreAction = { item: DocumentBean ->
            showDocumentHomeMoreDialog(item, null, this)
        }
        adapter?.itemClickAction = { item: DocumentBean ->
            if (item.type == TYPE_PDF) {
                PdfActivity.jumpPdfActivity(this, item)
            } else {
                jumpOtherDocument(item)
            }
        }

        arrayOf("All", "PDF", "Word", "Excel", "PPT").forEach { tab ->
            val tabBinding = ItemTabDocumentBinding.inflate(layoutInflater)
            tabBinding.tv.text = tab
            binding.tabLayout.addView(tabBinding.root)
        }
        binding.tabLayout.observeIndexChange { fromIndex, toIndex, reselect, fromUser ->
            if (!reselect) {
                when (toIndex) {
                    0 -> searchViewModel.searchMode = SEARCH_MODE_ALL
                    1 -> searchViewModel.searchMode = SEARCH_MODE_PDF
                    2 -> searchViewModel.searchMode = SEARCH_MODE_WORD
                    3 -> searchViewModel.searchMode = SEARCH_MODE_EXCEL
                    4 -> searchViewModel.searchMode = SEARCH_MODE_PPT
                }
                searchDocument()
            }
        }

        binding.edit.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                LogEx.logDebug(TAG, "actionDone")
                if (binding.edit.text.isNotEmpty()) {
                    searchDocument()
                }
            }
            false
        }


        searchDocument()
    }

    override fun initListener() {
        super.initListener()
        onBackPressedDispatcher.addCallback {
            finishToMain()
        }
        binding.flFanhui.setOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }
    }

    private fun searchDocument() {
        LogEx.logDebug(TAG, "searchDocument")
        val search = binding.edit.text.toString()
        lifecycleScope.launch(Dispatchers.IO) {
            val result = searchViewModel.getSearchDocument(this@SearchActivity, search)
            launch(Dispatchers.Main) {
                if (result.isEmpty()) {
                    binding.llEmpty.visibility = View.VISIBLE
                    adapter?.submitList(listOf())
                } else {
                    binding.llEmpty.visibility = View.GONE
                    adapter?.submitList(result)
                }
            }
        }
    }

    companion object {
        var SEARCH_MODE_ALL = "search_mode_all"
        var SEARCH_MODE_PDF = "search_mode_pdf"
        var SEARCH_MODE_WORD = "search_mode_word"
        var SEARCH_MODE_EXCEL = "search_mode_excel"
        var SEARCH_MODE_PPT = "search_mode_ppt"
    }

    override fun renameDocumentBean(file: File, newName: String) {
        try {
            val newFile = File(file.parentFile, newName)
            val result = file.renameTo(newFile)
            if (result) {
                searchDocument()
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun deleteDocument(item: DocumentBean) {
        val flag = File(item.path).delete()
        if (flag) {
            adapter?.remove(item)
        }
    }

}