/*-
 * ~~~~~~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.tracker;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.List;
import java.util.Map;

import org.osgi.framework.BundleContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ru.entaxy.esb.resources.EntaxyResource;
import ru.entaxy.esb.resources.EntaxyResourceService;
import ru.entaxy.esb.resources.EntaxyResourceService.EntaxyResourceProtocolAvailableCallback;
import ru.entaxy.esb.resources.tracker.ResourceProvider.ResourceDescriptor;
import ru.entaxy.platform.base.support.osgi.tracker.BundleTrackerCustomizerListener;

public class ResourceProviderCustomizerListener implements BundleTrackerCustomizerListener<List<ResourceProvider>> {

	private static final Logger log = LoggerFactory.getLogger(ResourceProviderCustomizerListener.class);
	
	protected BundleContext bundleContext; 
	
	protected EntaxyResourceService entaxyResourceService; 
	
	public ResourceProviderCustomizerListener(BundleContext context, EntaxyResourceService service) {
		this.bundleContext = context;
		this.entaxyResourceService = service;
	}
	
	@Override
	public void added(List<ResourceProvider> managedObject) {
		for (ResourceProvider provider: managedObject) {
			Map<String, List<ResourceDescriptor>> resources = provider.getResources();
			String message = "";
			message += "\nFOUND RESOURCES";
			for (String protocol: resources.keySet()) {
				
				if (!entaxyResourceService.isProtocolAvailable(protocol)) {
					log.info("Protocol [{}] not available, registering callback", protocol);
					entaxyResourceService.registerProtocolCallback(protocol
							, new ProtocolCallback(protocol, resources.get(protocol)));
					continue;
				}
				
				message += "\n\tPROTOCOL :: "  + protocol;
				List<ResourceDescriptor> list = resources.get(protocol);
				for (ResourceDescriptor rd: list) {
					message += "\n\t\t :: "  + rd.location + " | " + rd.url.toString();
				
					EntaxyResource resource = entaxyResourceService.getResource(protocol + ":" + rd.location);
					if (resource == null) {
						message += "\n\t\t -> NULL";
					} else {
						try (InputStream resourceStrem = rd.url.openStream()) {
							resource.save(resourceStrem);
							message += "\n\t\t -> " + resource.getAsString();
						} catch (IOException e) {
							log.error("Error saving resource", e);
						}
					}
						
				}
			}
			log.debug(message);
		}
		
	}

	@Override
	public void modified(List<ResourceProvider> managedObject) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void removed(List<ResourceProvider> managedObject) {
		// TODO Auto-generated method stub
		
	}

	protected class ProtocolCallback implements EntaxyResourceProtocolAvailableCallback {
		
		protected String protocol;
		protected List<ResourceDescriptor> descriptors;
		
		public ProtocolCallback(String protocol, List<ResourceDescriptor> descriptors) {
			this.protocol = protocol;
			this.descriptors = descriptors;
		}
		
		@Override
		public void protocolAvailable() {
			
			log.info("Protocol [{}] available, executing callback", protocol);
			
			for (ResourceDescriptor rd: descriptors) {
			
				EntaxyResource resource = entaxyResourceService.getResource(protocol + ":" + rd.location);
				if (resource != null) {
					try {
						resource.save(rd.url.openStream());
					} catch (IOException e) {
						log.error("Error saving resource", e);
					}
				}
					
			}
			
		}
		
	}
	
}
