package com.gh.gamecenter.qqmini

import android.annotation.TargetApi
import android.app.Application
import android.content.Context
import android.os.Build
import android.webkit.WebView
import java.io.File
import java.io.RandomAccessFile

object MiniGameWebViewUtils {
    fun handleWebViewDir(application: Application) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
            return
        }

        // Android P需要手动设置Data文件夹所在的进程，否则会触发以下异常：
        // java.lang.RuntimeException: Using WebView from more than one process at once with the same data directory is not supported.
        try {
            val processName = Application.getProcessName()
            val suffix = if (application.packageName != processName) {//判断不等于默认进程名称
                val process = processName.ifEmpty { application.packageName }
                WebView.setDataDirectorySuffix(process)
                "_$process"
            } else ""
            tryLockOrRecreateFile(application,suffix)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    @TargetApi(Build.VERSION_CODES.P)
    private fun tryLockOrRecreateFile(context: Context, suffix: String) {
        val sb = context.dataDir.absolutePath +
                "/app_webview"+suffix+"/webview_data.lock"
        val file = File(sb)
        if (file.exists()) {
            try {
                val tryLock = RandomAccessFile(file, "rw").channel.tryLock()
                if (tryLock != null) {
                    tryLock.close()
                } else {
                    createFile(file, file.delete());
                }
            } catch (e: Exception) {
                e.printStackTrace()
                val deleted = if (file.exists()) {
                    file.delete()
                } else false
                createFile(file, deleted)
            }
        }
    }

    private fun createFile(file: File, deleted: Boolean){
        try {
            if (deleted && !file.exists()) {
                file.createNewFile()
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}