package com.base.pdfviewerscannerwhite.ui.main

import android.content.Context
import androidx.lifecycle.LifecycleCoroutineScope
import com.base.pdfviewerscannerwhite.bean.ConstObject
import com.base.pdfviewerscannerwhite.bean.DocumentBean
import com.base.pdfviewerscannerwhite.utils.SpStringUtils
import com.base.pdfviewerscannerwhite.utils.getMediaFile
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.io.File

class DocumentPresenter(
    val documentView: DocumentView,
    val type: String,
    val lifecycleScope: LifecycleCoroutineScope
) {

    fun getDocumentBeanList(context: Context): List<DocumentBean> {
        var selectionArgs = arrayOf(ConstObject.MIME_TYPE_PDF)
        if (type == DocumentBean.TYPE_PDF) {
            selectionArgs = arrayOf(ConstObject.MIME_TYPE_PDF)
        }
        val bookmarkList = SpStringUtils.getSpStringList(SpStringUtils.BOOKMARK_KEY)

        val list = context.getMediaFile(selectionArgs = selectionArgs)
        val documentList = list.map {
            DocumentBean(it.path, uri = it.uri, type, bookmarkList.contains(it.path))
        }
        return documentList
    }

    fun initData(context: Context) = lifecycleScope.launch(Dispatchers.IO) {
        val documentList = getDocumentBeanList(context)
        launch(Dispatchers.Main) {
            documentView.refreshDocumentRv(documentList)
        }
    }

    fun saveBookmarkChange(addRemove: Boolean, path: String) {
        if (addRemove) {
            SpStringUtils.addSpString(SpStringUtils.BOOKMARK_KEY, path)
        } else {
            SpStringUtils.deleteSpString(SpStringUtils.BOOKMARK_KEY, path)
        }
    }

    fun renameDocumentBean(context: Context, file: File, newName: String) = lifecycleScope.launch(Dispatchers.IO) {

        runCatching {
            val nameFile = File(file.parentFile, newName)
            file.renameTo(nameFile)
        }
        val documentList = getDocumentBeanList(context)
        launch(Dispatchers.Main) {
            documentView.refreshDocumentRv(documentList)
        }
    }

    fun deleteDocumentBean(item: DocumentBean) {
        runCatching {
            val file = File(item.path)
            file.delete()
        }
    }


}