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

import com.atlassian.activeobjects.spi.AbstractBackupProgressMonitor;
import com.atlassian.bitbucket.i18n.I18nService;
import com.atlassian.bitbucket.util.Progress;
import com.atlassian.bitbucket.util.ProgressImpl;

/**
 * Implementation of AO's {@link com.atlassian.activeobjects.spi.BackupProgressMonitor} to track progress of the
 * AO backup.
 */
class AoBackupProgressMonitor extends AbstractBackupProgressMonitor {

    static final int SCHEMA_PROGRESS = 20;

    private final I18nService i18nService;

    private int tableCount;
    private int tablesProcessed;
    private volatile int progress;
    private volatile String i18nKey;

    public AoBackupProgressMonitor(I18nService i18nService) {
        this.i18nService = i18nService;

        i18nKey = "bitbucket.backup.backup.activeobjects";
    }

    @Override
    public void beginTableDefinitionsBackup() {
        i18nKey = "bitbucket.backup.activeobjects.backup.definitions";
    }

    @Override
    public void beginTablesBackup() {
        i18nKey = "bitbucket.backup.activeobjects.backup.data";
    }

    @Override
    public void endTableBackup(String tableName) {
        progress = SCHEMA_PROGRESS + ((++tablesProcessed * 80) / tableCount);
    }

    @Override
    public void endTableDefinitionsBackup() {
        progress = SCHEMA_PROGRESS;
    }

    @Override
    public void endTablesBackup() {
        progress = 100;
    }

    public Progress getProgress() {
        // this is calling i18nService.getText again to ensure we return the progress message in the locale of the
        // current user, instead of the locale of the user that started the maintenance task. This only works here
        // because all messages only use a simple key - without arguments.
        return new ProgressImpl(i18nService.getMessage(i18nKey), progress);
    }

    @Override
    public void updateTotalNumberOfTablesToBackup(int tableCount) {
        this.tableCount = tableCount;
    }
}
