/*-
 * ~~~~~~licensing~~~~~~
 * schema-impl
 * ==========
 * 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.esb.platform.runtime.core.infrastructure.schema.resolver.resource;

import java.io.File;
import java.nio.file.Files;
import java.util.Calendar;

import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.component.file.GenericFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ru.entaxy.esb.platform.runtime.core.infrastructure.schema.api.ResourceService;
import ru.entaxy.esb.platform.runtime.core.infrastructure.schema.api.entity.Resource;
import ru.entaxy.esb.platform.runtime.core.infrastructure.schema.api.entity.ResourceInfo;

public class ResourceLoader implements Processor {

	private static final Logger log = LoggerFactory.getLogger(ResourceLoader.class);
	
	protected ResourceService resourceService;

	public ResourceService getResourceService() {
		return resourceService;
	}

	public void setResourceService(ResourceService resourceService) {
		this.resourceService = resourceService;
	}

	@Override
	public void process(Exchange exchange) throws Exception {
		log.info("BODY IS [{}]\nHEADERS ARE:\n{}"
				, exchange.getIn().getBody().getClass().getName()
				, exchange.getIn().getHeaders().toString());
		String camelFileName = exchange.getIn().getHeader("CamelFilePath", String.class);
		String fileNameAndPath = camelFileName;//.substring(0, camelFileName.lastIndexOf("."));
		String fileName = getFileName(camelFileName);
		String filePath = getFilePath(camelFileName);
		String fileType = camelFileName.substring(camelFileName.lastIndexOf(".")+1);
		
		Resource resource = null;
		
		try {
			resource = resourceService.getResourceByFullName(fileNameAndPath).orElse(null);
		} catch (Exception e) {
			
		}
		if (resource ==null) {
			
			resource = new Resource();
			resource.setCreatedBy("admin");
			resource.setCreatedDate(Calendar.getInstance().getTime());
			
			GenericFile<?> genericFile = exchange.getIn().getBody(GenericFile.class);
			log.info("FILE IS {}", genericFile.getFile().getClass().getName());
			
			
			resource.setResourceValue(
				Files.readAllBytes(((File)genericFile.getFile()).toPath())
			);

			long resourceId = resourceService.loadResource(resource);
			
			ResourceInfo resourceInfo = new ResourceInfo();
			resourceInfo.setCreatedBy("admin");
			resourceInfo.setCreatedDate(Calendar.getInstance().getTime());
			resourceInfo.setConvertor(false);
			resourceInfo.setDescription("Automatically loaded with type [" + fileType + "]");


			resourceInfo.setName(fileName);
			resourceInfo.setPath(filePath);

			resourceInfo.setVersion("1.0");
			resourceInfo.setResourceId(resourceId);
			
			long resourceInfoId = resourceService.loadResourceInfo(resourceInfo);
			
			log.info("ResourceInfo id is [" + resourceInfoId + "]");
			
		} else {
			GenericFile<?> genericFile = exchange.getIn().getBody(GenericFile.class);
			log.info("FILE IS {}", genericFile.getFile().getClass().getName());
			
			
			resource.setResourceValue(
				Files.readAllBytes(((File)genericFile.getFile()).toPath())
			);
			
			resourceService.reloadResource(resource);
		}
		
	}

	private String getFileName(String fileNameAndPath) {
		String[] splitted = fileNameAndPath.split(File.separator);
		return splitted[splitted.length-1];
	}

	private String getFilePath(String fileNameAndPath) {
		String[] splitted = fileNameAndPath.split(File.separator);
		String path = null;
		if (splitted.length>1) {
			path = fileNameAndPath.substring(0, fileNameAndPath.length() - splitted[splitted.length-1].length());
		}
		return path;
	}
}
