package ch.threema.app.systemupdates.updates

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import ch.threema.app.files.WallpaperFileHandleProvider
import ch.threema.base.utils.getThreemaLogger
import ch.threema.localcrypto.MasterKeyProvider
import java.io.File
import org.koin.core.component.inject

private val logger = getThreemaLogger("SystemUpdateToVersion114")

class SystemUpdateToVersion114 : SystemUpdate {

    private val appContext: Context by inject()
    private val masterKeyProvider: MasterKeyProvider by inject()
    private val wallpaperFileHandleProvider: WallpaperFileHandleProvider by inject()

    override fun run() {
        try {
            val legacyDataDirectory = File(appContext.getExternalFilesDir(null), "data")
            val legacyGlobalWallpaperFile = File(legacyDataDirectory, "wallpaper.jpg")
            if (!legacyGlobalWallpaperFile.exists()) {
                return
            }

            val masterKey = masterKeyProvider.getMasterKey()

            val options = BitmapFactory.Options()
            options.inSampleSize = 1
            options.inPreferredConfig = Bitmap.Config.RGB_565

            val bitmap = legacyGlobalWallpaperFile.inputStream().use { inputStream ->
                BitmapFactory.decodeStream(inputStream, null, options)
            }
            val isAlreadyEncrypted = bitmap == null
            bitmap?.recycle()

            legacyGlobalWallpaperFile.inputStream()
                .let { inputStream ->
                    if (isAlreadyEncrypted) {
                        masterKey.decrypt(inputStream)
                    } else {
                        inputStream
                    }
                }
                .use { inputStream ->
                    wallpaperFileHandleProvider.getGlobal().write().use { outputStream ->
                        inputStream.copyTo(outputStream)
                    }
                }

            legacyGlobalWallpaperFile.delete()
        } catch (e: Exception) {
            logger.warn("Failed to migrate global wallpaper", e)
        }
    }

    override val version = 114

    override fun getDescription() = "move (and encrypt) global wallpaper file"
}
