package com.kdanmobile.reader.copyfile

import android.content.Context
import android.content.Intent
import android.net.Uri
import com.kdanmobile.reader.utils.UriToPathUtil
import java.io.File
import java.util.regex.Pattern

class CopyFileInfoFactory {
    fun createInfo(applicationContext: Context, intent: Intent, kdanPdfReaderFolder: File): CopyFileInfo {
        val shouldCopyFile = intent.getBooleanExtra(CopyFileActivity.KEY_SHOULD_COPY_FILE, true)
        val isActionView = intent.action == Intent.ACTION_VIEW
        val srcFilePath = if (intent.action == Intent.ACTION_VIEW) {
            getFilePathFromUri(applicationContext, intent.data, kdanPdfReaderFolder)
        } else {
            intent.getStringExtra(CopyFileActivity.KEY_FILE_ABSOLUTE_PATH)
        }
        val uri = intent.data
        return CopyFileInfo(shouldCopyFile, isActionView, srcFilePath, uri)
    }

    private fun getFilePathFromUri(applicationContext: Context, uri: Uri?, kdanPdfReaderFolder: File): String? {
        if (null == uri) return null
        var filePath = UriToPathUtil.getInstance().getPath(applicationContext, uri)
        //  workaround
        if (filePath.isNullOrEmpty() && null != uri.path) {
            val folderName = kdanPdfReaderFolder.name
            val pattern = Pattern.compile("$folderName/.*\\.(([Pp][Dd][Ff])|([Ee][Pp][Uu][Bb]))")
            val matcher = pattern.matcher(uri.path)
            if (matcher.find()) {
                val path = "${kdanPdfReaderFolder.absolutePath}/${matcher.group().substring(folderName.length)}"
                val file = File(path)
                if (file.exists()) {
                    filePath = file.absolutePath
                }
            }
        }
        if (null != filePath && !File(filePath).exists()) {
            filePath = Uri.decode(filePath)
        }
        return if (null != filePath && File(filePath).exists()) filePath else null
    }
}