/*-
 * ~~~~~~licensing~~~~~~
 * resources-management
 * ==========
 * 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.resources.management.impl;

import javax.management.NotCompliantMBeanException;

import org.apache.commons.io.IOUtils;
import ru.entaxy.esb.platform.base.management.core.api.AnnotatedMBean;
import ru.entaxy.esb.resources.EntaxyResource;
import ru.entaxy.esb.resources.EntaxyResourceMetadata.MetadataSection;
import ru.entaxy.esb.resources.EntaxyResourceProvider;
import ru.entaxy.esb.resources.management.EntaxyResourceProviderMBean;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Base64;

public class EntaxyResourceProviderMBeanImpl extends AnnotatedMBean<EntaxyResourceProviderMBean>
	implements EntaxyResourceProviderMBean{
	
	protected EntaxyResourceProvider resourceProvider;

	protected EntaxyResourceProviderMBeanImpl(EntaxyResourceProvider provider) throws NotCompliantMBeanException {
		super(EntaxyResourceProviderMBean.class);
		this.resourceProvider = provider;
	}

	@Override
	public String getProtocol() {
		return this.resourceProvider.getProtocol();
	}

	@Override
	public List<Map<String, Object>> getResourcesInfo(String path) throws Exception {
		List<EntaxyResource> resources = resourceProvider.getResources(path);
		List<Map<String, Object>> resourcesInfo = new ArrayList<>();

		if (resources != null) {
			for (EntaxyResource resource : resources) {
				Map<String, Object> resourceInfo = new HashMap<>();

				resourceInfo.put("name", resource.getName());
				resourceInfo.put("isFolder", resource.isFolder());
				if (resource.hasMetadata()) {
					Map<String, String> metadata = new HashMap<>();
					for (MetadataSection section : resource.getMetadata().getSections()) {
						metadata.put(section.getName(), section.getContent().toString());
					}
					resourceInfo.put("metadata", metadata);
				}

				resourcesInfo.add(resourceInfo);
			}
		}

		return resourcesInfo;
	}

	@Override
	public String downloadResource(String path) throws Exception {
		try (InputStream is = resourceProvider.getResource(path).getInputStream()) {
			return Base64.getEncoder().encodeToString(readFromStream(is));
		}
	}

	private byte[] readFromStream(InputStream is) throws IOException {
		try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
			IOUtils.copy(is, baos);
			return baos.toByteArray();
		} catch (IOException e) {
			throw e;
		}
	}

	@Override
	public void pasteResource(String from, String to) throws Exception {
		if (ServiceHelper.INSTANCE == null) {
			throw new IllegalStateException("Service helper is not initialized");
		}

		EntaxyResource sourceResource = ServiceHelper.INSTANCE.entaxyResourceService.getResource(from);
		pasteResource(sourceResource, to);
	}

	private void pasteResource(EntaxyResource sourceResource, String to) throws Exception {
		if (sourceResource.exists()) {
			if (sourceResource.isFolder()) {
				List<EntaxyResource> resources = ServiceHelper.INSTANCE.entaxyResourceService
						.getResources(sourceResource.getURL());
				for(EntaxyResource resource : resources) {
					pasteResource(resource, to + '/' + resource.getName());
				}
			} else {
				try (InputStream is = sourceResource.getInputStream()) {
					EntaxyResource targetResource = resourceProvider.getResource(to);
					targetResource.save(is);
				}
			}
		} else {
			throw new IllegalArgumentException("Resource located at [" + sourceResource.getURL() + "] is not found");
		}
	}

	@Override
	public void removeResource(String path) throws Exception {
		if (path.contains(":")) {
			if (ServiceHelper.INSTANCE == null) {
				throw new IllegalStateException("Service helper is not initialized");
			}

			ServiceHelper.INSTANCE.entaxyResourceService.getResource(path).delete();
		} else {
			resourceProvider.getResource(path).delete();
		}
	}

	@Override
	public void saveResource(String path, String content) throws Exception {
		try (InputStream is = IOUtils.toInputStream(content)) {
			resourceProvider.getResource(path).save(is);
		}
	}
}
