package com.example.onetap_ssh.backup;

import android.content.Context;
import android.net.Uri;
import android.util.Base64;

import com.example.onetap_ssh.crypto.CryptoException;
import com.example.onetap_ssh.crypto.CryptoParameters;
import com.example.onetap_ssh.util.BackupException;
import com.example.onetap_ssh.util.IOUtil;

import com.example.onetap_ssh.util.SettingsUtil;
import com.google.gson.JsonSyntaxException;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import javax.crypto.SecretKey;

public class BackupUtil {

    private static final SimpleDateFormat FORMAT = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss", Locale.ENGLISH);

    public static String getBackupName() {
        return "code_guard_backup_" + FORMAT.format(new Date());
    }

    public static void saveBackup(Context context, Uri backupFile, SecretKey key, CryptoParameters parameters) throws BackupException, CryptoException {

    }

    public static CryptoParameters loadParametersFromBackup(Context context, Uri backupFile) throws BackupException {
        try(InputStream in = context.getContentResolver().openInputStream(backupFile)) {
            if(in == null) throw new BackupException("Failed to read backup file");
            byte[] backupBytes = IOUtil.readBytes(in);
            BackupData data = SettingsUtil.GSON.fromJson(new String(backupBytes, StandardCharsets.UTF_8), BackupData.class);
            if(!data.getParameters().isValid()) throw new BackupException("Invalid crypto parameters");
            return data.getParameters();
        } catch (JsonSyntaxException e) {
            throw new BackupException("Invalid JSON", e);
        } catch (IOException e) {
            throw new BackupException(e);
        }
    }

    public static BackupData loadBackup(Context context, Uri backupFile) throws BackupException {
        try (InputStream in = context.getContentResolver().openInputStream(backupFile)) {
            if (in == null) throw new BackupException("Failed to read backup file");
            byte[] backupBytes = IOUtil.readBytes(in);
            BackupData data = SettingsUtil.GSON.fromJson(new String(backupBytes, StandardCharsets.UTF_8), BackupData.class);
            if(!data.isValid()) throw new BackupException("Invalid backup data"); // TODO: more info on backup errors
            return data;
        } catch (JsonSyntaxException e) {
            throw new BackupException("Invalid JSON", e);
        } catch (IOException e) {
            throw new BackupException(e);
        }
    }

}
