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

import com.atlassian.stash.internal.maintenance.CompositeMaintenanceTask;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Nonnull;
import java.io.File;

public class RestorePhase extends CompositeMaintenanceTask {

    private static final Logger log = LoggerFactory.getLogger(RestorePhase.class);

    private final RestoreState state;

    protected RestorePhase(RestoreState state, Step[] steps, int totalWeight) {
        super(steps, totalWeight);

        this.state = state;
    }

    @Override
    public void run() {
        try {
            super.run();
        } finally {
            File unpackedDirectory = state.getUnzippedBackupDirectory();
            if (unpackedDirectory != null && unpackedDirectory.exists()) {
                if (FileUtils.deleteQuietly(unpackedDirectory)) {
                    log.debug("Successfully deleted unpacked files from {}", unpackedDirectory.getAbsolutePath());
                } else {
                    log.warn("Failed to delete unpacked files at {}; the directory has been marked for deletion on exit",
                            unpackedDirectory.getAbsolutePath());
                    //TODO: Apply this to every file and directory
                    unpackedDirectory.deleteOnExit();
                }
            }
        }
    }

    public static class Builder extends CompositeMaintenanceTask.AbstractBuilder<Builder> {
        private final RestoreState state;

        public Builder(RestoreState state) {
            this.state = state;
        }

        @Nonnull
        @Override
        public RestorePhase build() {
            return new RestorePhase(state, steps.toArray(new Step[steps.size()]), totalWeight);
        }

        @Override
        protected Builder self() {
            return this;
        }
    }
}
