package ch.threema.app.systemupdates.updates;

import android.content.Context;
import android.database.Cursor;

import org.koin.java.KoinJavaComponent;
import org.slf4j.Logger;

import java.io.File;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import ch.threema.app.utils.FileUtil;
import ch.threema.common.Base32;
import ch.threema.storage.DatabaseProvider;
import kotlin.Lazy;

import static android.provider.MediaStore.MEDIA_IGNORE_FILENAME;
import static ch.threema.base.utils.LoggingKt.getThreemaLogger;
import static ch.threema.common.JavaCompat.isNullOrEmpty;

public class SystemUpdateToVersion42 implements SystemUpdate {
    private static final Logger logger = getThreemaLogger("SystemUpdateToVersion42");

    private final Lazy<Context> appContextLazy = KoinJavaComponent.inject(Context.class);
    private final Lazy<DatabaseProvider> databaseProviderLazy = KoinJavaComponent.inject(DatabaseProvider.class);

    @Override
    public void run() {
        var appContext = appContextLazy.getValue();

        final File appPath = new File(appContext.getExternalFilesDir(null), "data");
        final File avatarPath = new File(appPath, "/.avatar");
        final File wallpaperPath = new File(appPath.getPath() + "/.wallpaper");

        var database = databaseProviderLazy.getValue().getReadableDatabase();

        Cursor contacts = database.rawQuery("SELECT identity FROM contacts", null);
        if (contacts != null) {
            while (contacts.moveToNext()) {
                final String identity = contacts.getString(0);

                if (!isNullOrEmpty(identity)) {
                    migratePictureFile(avatarPath, ".c-", null, "c-" + identity, identity);
                    migratePictureFile(avatarPath, ".p-", null, "c-" + identity, identity);
                    migratePictureFile(wallpaperPath, ".w-", ".w", "c-" + identity, null);
                }
            }
            contacts.close();
        }

        Cursor groups = database.rawQuery("SELECT id FROM m_group", null);
        if (groups != null) {
            while (groups.moveToNext()) {
                final int id = groups.getInt(0);

                if (id >= 0) {
                    migratePictureFile(wallpaperPath, ".w-", ".w", "g-" + String.valueOf(id), null);
                }
            }
            groups.close();
        }

        // delete obsolete distribution list wallpaper
        File distributionListWallpaper = new File(wallpaperPath, ".w0" + MEDIA_IGNORE_FILENAME);
        try {
            FileUtil.deleteFileOrWarn(distributionListWallpaper, "", logger);
        } catch (Exception e) {
            //
        }
    }

    private boolean migratePictureFile(File path, String filePrefix, String oldFilePrefix, String rawUniqueId, String oldRawUniqueId) {
        String filename_old = (oldFilePrefix != null ? oldFilePrefix : filePrefix) + String.valueOf(oldRawUniqueId != null ? oldRawUniqueId : rawUniqueId).hashCode() + MEDIA_IGNORE_FILENAME;
        String filename_new;

        try {
            MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
            messageDigest.update(rawUniqueId.getBytes());
            filename_new = filePrefix + Base32.encode(messageDigest.digest()) + MEDIA_IGNORE_FILENAME;
        } catch (NoSuchAlgorithmException e) {
            logger.error("Exception", e);
            return false;
        }

        File oldFile = new File(path, filename_old);
        File newFile = new File(path, filename_new);

        if (oldFile.exists()) {
            try {
                if (newFile.exists()) {
                    FileUtil.deleteFileOrWarn(oldFile, "", logger);
                } else {
                    if (!oldFile.renameTo(newFile)) {
                        logger.debug("Failed to rename file");
                    }
                }
            } catch (Exception e) {
                //
            }
        }
        return true;
    }

    @Override
    public int getVersion() {
        return 42;
    }
}
