/*-
 * ~~~~~~licensing~~~~~~
 * core-support-runtime
 * ==========
 * Copyright (C) 2020 - 2025 EmDev LLC
 * ==========
 * You may not use this file except in accordance with the License Terms of the Copyright
 * Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
 * rights to the Software and any copies are the property of the Copyright Holder. Unless
 * it is explicitly allowed the Copyright Holder, the User is prohibited from using the
 * Software for commercial purposes to provide services to third parties.
 * 
 * The Copyright Holder hereby declares that the Software is provided on an "AS IS".
 * Under no circumstances does the Copyright Holder guarantee or promise that the
 * Software provided by him will be suitable or not suitable for the specific purposes
 * of the User, that the Software will meet all commercial and personal subjective
 * expectations of the User, that the Software will work properly, without technical
 * errors, quickly and uninterruptedly.
 * 
 * Under no circumstances shall the Copyright Holder or its Affiliates is not liable
 * to the User for any direct or indirect losses of the User, his expenses or actual
 * damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
 * or damage to data, property, etc.
 * ~~~~~~/licensing~~~~~~
 */
package ru.entaxy.platform.core.support.runtime;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.stream.Stream;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ru.entaxy.esb.resources.EntaxyResource;
import ru.entaxy.platform.core.support.runtime.helper.ServiceHelper;

public class EntaxyResourceUtils {

	private static final Logger log = LoggerFactory.getLogger(EntaxyResourceUtils.class);
	
	static final String RESOURCE_PROTOCOL = "entaxy-resource";
	
	public static String getOwnResourceUrl(String resourceUrl) {
		String result = resourceUrl;
		if (result.startsWith(RESOURCE_PROTOCOL))
			result = result.substring(RESOURCE_PROTOCOL.length());
		result = StringUtils.stripStart(result, ":/");
		
		int index = result.indexOf(':');
		if (index > 0)
			return result;
		
		result = StringUtils.replaceOnce(result, "/", ":");
		
		return result;
	}
	
	public static void uploadFolder(String folderPath, String targetResourceFolderUrl) throws IOException {
		
		String targetUrl = getOwnResourceUrl(targetResourceFolderUrl);
		targetUrl = StringUtils.stripEnd(targetUrl, "/");
		
		File rootFolder = new File(folderPath);
		if (!rootFolder.exists())
			return;
		
		if (!rootFolder.isDirectory())
			return;
		
		final Path rootPath = rootFolder.toPath();
		
		final String resourceRootFolderUrl = targetUrl;
		
		try (Stream<Path> pathStream = Files.walk(rootPath)) {
			pathStream.forEach(path -> uploadFile(path, rootPath, resourceRootFolderUrl));
		}
	}
	
	public static void uploadFile(Path filePath, Path rootPath, String resourceRootFolderUrl) {
		
		File f = filePath.toFile();
		if (f.isDirectory())
			return;
		Path relative = rootPath.relativize(filePath);
		String targetResource = resourceRootFolderUrl + "/" + relative.toString().replace('\\', '/');
	
		if (ServiceHelper.getIinstance() == null) {
			log.error("ServiceHelper NOT READY");
			return;
		}
		
		log.debug(String.format("++ UPLOADING :: [%s] -> [%s]"
				, filePath.toAbsolutePath()
				, targetResource));

		EntaxyResource resource = ServiceHelper.getIinstance().getEntaxyResourceService()
				.getResource(targetResource);
		try (InputStream is = new FileInputStream(f)) {
			resource.save(is);
		} catch (Exception e) {
			log.error("Error saving resource", e);
		}
	}

	public static File downloadFile(Path filePath, String resourceUrl) throws Exception {
		
		if (!resourceUrl.startsWith(RESOURCE_PROTOCOL))
			return null;
		
		URL urlToLoad = new URL(resourceUrl); 
		
		File f = filePath.toFile();
		if (f.isDirectory())
			return null;
		
		if (f.exists()) {
			f.delete();
		}
		
		f.getParentFile().mkdirs();
		
		try (
				FileOutputStream fileOutputStream = new FileOutputStream(f);
				InputStream inputStream = urlToLoad.openConnection().getInputStream()
						){
			FileChannel channel = fileOutputStream.getChannel();
			FileLock lock = channel.lock();
		    byte[] bytes = IOUtils.toByteArray(inputStream);
		    channel.write(ByteBuffer.wrap(bytes));
		     
		    lock.release();
		    channel.close();
		} catch (Exception e) {
			throw e;
		}

		return f;
	}	
	
}
