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

import java.io.IOException;
import java.io.InputStream;
import java.io.StringBufferInputStream;
import java.net.URL;
import java.net.URLConnection;

import org.apache.commons.io.IOUtils;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.annotations.ReferenceCardinality;
import org.osgi.service.component.annotations.ServiceScope;
import org.osgi.service.url.AbstractURLStreamHandlerService;
import org.osgi.service.url.URLStreamHandlerService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ru.entaxy.esb.resources.EntaxyResource;
import ru.entaxy.esb.resources.EntaxyResourceMetadata;
import ru.entaxy.esb.resources.EntaxyResourceService;
import ru.entaxy.platform.base.support.CommonUtils;

@Component(service = URLStreamHandlerService.class, property = "url.handler.protocol=entaxy-resource"
, immediate = true, scope = ServiceScope.SINGLETON)
public class EntaxyResourcesURLHandler extends AbstractURLStreamHandlerService {

	private static final Logger log = LoggerFactory.getLogger(EntaxyResourcesURLHandler.class);
	
	static final String HASH_TIMESTAMP = "timestamp";
	
	@Reference (cardinality = ReferenceCardinality.MANDATORY)
	protected EntaxyResourceService entaxyResourceService;
	
	protected static class EntaxyResourcesURLConnection extends URLConnection {

		protected EntaxyResourceService resourceService;
		
		protected String resourceUrl;
		
		protected EntaxyResourcesURLConnection(URL url, EntaxyResourceService resourceService) {
			super(url);
			this.resourceService = resourceService;
			resourceUrl = url.toString().substring(url.toString().indexOf(":")+1);
			
			// if used hierarchical URI format
			// entaxy-resource://<resource-provider>/<resource-path>
			while (resourceUrl.startsWith("//"))
				resourceUrl = resourceUrl.substring(2);
			if (resourceUrl.indexOf(':')<0) {
				// replace first '/' with ':'
				int index = resourceUrl.indexOf('/');
				if (index<0) {
					resourceUrl = resourceUrl + ':';
				} else {
					resourceUrl = resourceUrl.replaceFirst("/", ":");
				}
			}
		}

		@Override
		public void connect() throws IOException {
			// NOOP
		}
		
		@Override
		public InputStream getInputStream() throws IOException {
			
			String targetUrl = resourceUrl;
			String hash = "";
			
			int hashIndex = resourceUrl.indexOf('#'); 
			if (hashIndex > 0) {
				targetUrl = resourceUrl.substring(0, hashIndex);
				hash = resourceUrl.substring(hashIndex + 1);
			}
			
			EntaxyResource resource = resourceService.getResource(targetUrl);
			if (!resource.exists())
				throw new IllegalArgumentException("Resource not found: [" + resourceUrl + "]");
			if (CommonUtils.isValid(hash)) {
				if (HASH_TIMESTAMP.equalsIgnoreCase(hash)) {
					String value = resource.getTimestamp(); /* "0";
					EntaxyResourceMetadata erm = resource.getMetadata();
					if (erm != null) {
						EntaxyResourceMetadata.MetadataSection section = erm.getSection(EntaxyResourceMetadata.SECTION_RESOURCE.NAME);
						if ((section != null) && section.getContent().has(HASH_TIMESTAMP)) {
							try {
								value = section.getContent().get(HASH_TIMESTAMP).getAsString();
							} catch (Exception e) {
								// ignore
							}
						}
					} */
					return IOUtils.toInputStream(value);
				}
			} 
			return resource.getInputStream();
		}
		
	} 
	
	@Override
	public URLConnection openConnection(URL u) throws IOException {
		return new EntaxyResourcesURLConnection(u, entaxyResourceService);
	}

}
