package com.gh.gamecenter.xapk.io

import android.os.Environment
import com.gh.gamecenter.xapk.XApkUnZipTask
import com.gh.gamecenter.xapk.data.XApkManifest
import com.gh.gamecenter.xapk.pi.IPackageInstaller
import com.gh.gamecenter.xapk.pi.NonSplitPackagesInstaller
import java.io.File
import java.io.FileOutputStream

class NonSplitApksOutput(
    private val parentFile: File = File(
        Environment.getExternalStorageDirectory(),
        DEFAULT_PARENT_FILE_PATH
    ),
    private val factory: (File) -> IPackageInstaller = {
        NonSplitPackagesInstaller(it)
    }
) : XApkFileOutput<IPackageInstaller> {

    companion object {
        const val DEFAULT_PARENT_FILE_PATH = "Download"
    }

    override fun output(
        writer: XApkUnZipTask.XApkWriter,
        manifest: XApkManifest
    ): IPackageInstaller = manifest.splitApks[0]
        .let { apk ->
            File(parentFile, "${manifest.packageName}/${apk.file}")
                .apply {
                    val parentFile = parentFile
                    if (parentFile != null && !parentFile.exists()) {
                        parentFile.mkdirs()
                    }
                    if (!exists()) createNewFile()
                }
                .also {
                    writer.write(apk.file, FileOutputStream(it))
                }
                .let {
                    factory.invoke(it)
                }
        }


}