package com.atlassian.stash.internal.home;

import com.atlassian.bitbucket.util.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;

public class HomeFileMover implements FileMover {
    private static final Logger log = LoggerFactory.getLogger(HomeFileMover.class);

    private final FileMover fileMover;

    public HomeFileMover(FileMover fileMover) {
        this.fileMover = fileMover;
    }

    @Override
    public void move(File source, File target) throws IOException {
        if (!source.exists()) {
            // If the source directory does not exist we assume that one of two facts is valid:
            //  - We are operating on a clean/new home directory so this directory simply does not exist
            //  - It already has been migrated to its target position
            // In both cases there is nothing more to be done.
            return;
        }

        if (target.exists()) {
            // At this point both source and target exist. We assume that one of two things has happened:
            //  - A migration has failed
            //  - Somebody is fiddling the home directory layout and its not quite right
            // In both cases we want this fact to communicated as quickly as possible
            throw new HomeDirectoryMigrationException("The '" + target.getName() + "' directory exists on both " +
                    source.getAbsolutePath() + " and " + target.getAbsolutePath() + ".");
        }

        try {
            FileUtils.mkdir(target.getParentFile());
        } catch (IllegalArgumentException | IllegalStateException | NullPointerException e) {
            throw new HomeDirectoryMigrationException("'" + target.getParent() + "'  could not be created.", e);
        }

        log.info("Moving {} to {}", source.getAbsolutePath(), target.getAbsolutePath());
        fileMover.move(source, target);
        log.debug("Moving {} to {} successful", source.getAbsolutePath(), target.getAbsolutePath());
    }
}
