package db;

import java.io.File;
import java.io.IOException;
import java.nio.file.*;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Comparator;

public class DatabaseBackupRunner {

    private static final String REQUIRED_USER = "cbu615";
    private static final String BACKUP_DIR = "V:\\Schulungsstatistik_Backup";
    private static final String DB_FILE = util.Config.getDbPath();
    private static final DateTimeFormatter FMT = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    /** Call this once on program start */
    public static void runBackupCheck() {
        if (!System.getProperty("user.name").equalsIgnoreCase(REQUIRED_USER)) return;
        

        File backupFolder = new File(BACKUP_DIR);
        if (!backupFolder.exists()) backupFolder.mkdirs();

        LocalDate newest = findNewestBackupDate(backupFolder);

        if (newest == null || newest.isBefore(LocalDate.now().minusDays(7))) {
        	System.out.println("creating backup...");
            createBackup(backupFolder);            
        } else
        {
        	System.out.println("no backup needed; last backup in " + BACKUP_DIR + " (" + newest.format(DateTimeFormatter.ISO_LOCAL_DATE) + ")");
        }
    }
    //delete this

    private static LocalDate findNewestBackupDate(File folder) {
        File[] files = folder.listFiles((dir, name) -> name.startsWith("backup_") && name.endsWith(".db"));
        if (files == null || files.length == 0) return null;

        return java.util.Arrays.stream(files)
            .map(f -> {
                try {
                    String datePart = f.getName().substring("backup_".length(), "backup_".length() + 10);
                    return LocalDate.parse(datePart, FMT);
                } catch (Exception e) {
                    return null;
                }
            })
            .filter(d -> d != null)
            .max(Comparator.naturalOrder())
            .orElse(null);
    }

    private static void createBackup(File folder) {
        String date = LocalDate.now().format(FMT);
        File target = new File(folder, "backup_" + date + ".db");       

        try {
            Files.copy(
                Paths.get(DB_FILE),
                target.toPath(),
                StandardCopyOption.REPLACE_EXISTING
            );
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
