package com.atlassian.stash.internal.maintenance.backup;

import com.atlassian.bitbucket.i18n.SimpleI18nService;
import org.junit.Before;
import org.junit.Test;

import static com.atlassian.stash.internal.maintenance.backup.AoBackupProgressMonitor.SCHEMA_PROGRESS;
import static com.atlassian.stash.internal.maintenance.MaintenanceTaskTestHelper.assertProgress;

public class AoBackupProgressMonitorTest {

    private AoBackupProgressMonitor monitor;

    @Before
    public void setUp() {
        monitor = new AoBackupProgressMonitor(new SimpleI18nService(SimpleI18nService.Mode.RETURN_KEYS));
    }

    @Test
    public void testMonitor() {
        assertProgress("bitbucket.backup.backup.activeobjects", 0, monitor.getProgress());

        monitor.beginBackup();
        monitor.beginDatabaseInformationBackup();
        assertProgress("bitbucket.backup.backup.activeobjects", 0, monitor.getProgress());

        monitor.beginTableDefinitionsBackup();
        assertProgress("bitbucket.backup.activeobjects.backup.definitions", 0, monitor.getProgress());

        monitor.endTableDefinitionsBackup();
        assertProgress("bitbucket.backup.activeobjects.backup.definitions", SCHEMA_PROGRESS, monitor.getProgress());

        monitor.beginTablesBackup();
        assertProgress("bitbucket.backup.activeobjects.backup.data", SCHEMA_PROGRESS, monitor.getProgress());

        int tableCount = 5;
        monitor.updateTotalNumberOfTablesToBackup(tableCount);
        assertProgress("bitbucket.backup.activeobjects.backup.data", SCHEMA_PROGRESS, monitor.getProgress());

        // each table contributes evenly to progress.
        int tableProgress = (100 - SCHEMA_PROGRESS) / tableCount;
        for (int i = 0; i < tableCount; ++i) {
            monitor.beginTableBackup("table " + i);
            assertProgress("bitbucket.backup.activeobjects.backup.data", SCHEMA_PROGRESS + i * tableProgress,
                    monitor.getProgress());
            monitor.endTableBackup("table " + i);
            assertProgress("bitbucket.backup.activeobjects.backup.data", SCHEMA_PROGRESS + (i + 1) * tableProgress,
                    monitor.getProgress());
        }

        monitor.endTablesBackup();
        assertProgress("bitbucket.backup.activeobjects.backup.data", 100, monitor.getProgress());

        monitor.endBackup();
        assertProgress("bitbucket.backup.activeobjects.backup.data", 100, monitor.getProgress());
    }
}
