/*-
 * ~~~~~~licensing~~~~~~
 * file-system-deployer
 * ==========
 * Copyright (C) 2020 - 2021 EmDev LLC
 * ==========
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ~~~~~~/licensing~~~~~~
 */
package ru.entaxy.esb.system.deployer.file;

import ru.entaxy.esb.system.deployer.api.BundleRepository;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.regex.Matcher;

public class FileSystemRepositoryImpl implements BundleRepository {

    private String folderRoot;

    @Override
    public String deployBlueprint(String groupId, String version, String name, String extension, byte[] data) throws Exception {
        Path path = preparePath(groupId, version, name, extension);
        if (!Files.exists(path.getParent())) {
            Files.createDirectories(path.getParent());
        }
        Files.write(path, data);
        return "blueprint:file:" + path.normalize();
    }

    @Override
    public void delete(String groupId, String version, String name, String extension) throws Exception {
        Files.deleteIfExists(preparePath(groupId, version, name, extension));
    }

    private Path preparePath(String groupId, String version, String name, String extension) {
        String gpoupIdPath = groupId.replaceAll("\\.", Matcher.quoteReplacement(File.separator));
        String fileName = name + "-" + version + "." + extension;
        Path path = Paths.get(folderRoot, gpoupIdPath, fileName);
        return path;
    }

    public String getFolderRoot() {
        return folderRoot;
    }

    public void setFolderRoot(String folderRoot) {
        this.folderRoot = folderRoot;
    }

}
