package de.nbscloud.files;

import de.nbscloud.files.config.FilesConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.file.Path;
import java.nio.file.Paths;

@Component
public class LocationTracker {
    @Autowired
    private FilesConfig filesConfig;

    private Path baseDirPath;
    private Path currentLocation;

    public void init() {
        this.baseDirPath = Paths.get(this.filesConfig.getBaseDir());
        this.currentLocation = baseDirPath.resolve("");
    }

    public void reset() {
        init();
    }

    public Path getCurrentLocation() {
        return this.currentLocation;
    }

    public void setCurrentLocation(String navigateTo) {
        validate(navigateTo);

        this.currentLocation = this.currentLocation.resolve(navigateTo);
    }

    private void validate(String navigateTo) {
        if(navigateTo == null) {
            throw new IllegalStateException("Null");
        }

        if(navigateTo.contains("..")) {
            throw new IllegalStateException("Relative path");
        }

        if (Paths.get(navigateTo).isAbsolute()) {
            throw new IllegalStateException("Absolute path: " + navigateTo);
        }

        if(!this.currentLocation.resolve(navigateTo).startsWith(this.baseDirPath)) {
            throw new IllegalStateException("Illegal path: " + navigateTo);
        }
    }
}
