/*-
 * ~~~~~~licensing~~~~~~
 * file-adapter
 * ==========
 * Copyright (C) 2020 - 2022 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.platform.adapter.file;

import java.io.File;
import java.util.Map;

import org.apache.camel.component.file.FileComponent;
import org.apache.camel.component.file.GenericFileEndpoint;
import org.apache.camel.util.StringHelper;

import ru.entaxy.platform.base.support.CommonUtils;

public class ExtendedFileComponent extends FileComponent {

	protected String rootDirectory = "";

	@Override
	protected GenericFileEndpoint<File> buildFileEndpoint(String uri, String remaining, Map<String, Object> parameters)
			throws Exception {
		
		// copied from parent 
        if (StringHelper.hasStartToken(remaining, "simple")) {
            throw new IllegalArgumentException("Invalid directory: " + remaining + ". Dynamic expressions with ${ } placeholders is not allowed."
                                               + " Use the fileName option to set the dynamic expression.");
        }
		
		String current = remaining;
		if (CommonUtils.isValid(rootDirectory)) {
			current = rootDirectory;
			if (CommonUtils.isValid(remaining) && !".".equals(remaining)) {
				if (!current.endsWith("/"))
					current += "/";
				if (remaining.startsWith("/"))
					current += remaining.substring(1);
				else
					current += remaining;
			}
		}
		log.debug("CREATING ENDPOINT FOR [{}]", current);
		return super.buildFileEndpoint(uri, current, parameters);
	}
	
	public String getRootDirectory() {
		return rootDirectory;
	}

	public void setRootDirectory(String rootDirectory) {
		this.rootDirectory = rootDirectory;
	}
	
}
