/*-
 * ~~~~~~licensing~~~~~~
 * connection-initializer
 * ==========
 * Copyright (C) 2020 - 2021 EmDev LLC
 * ==========
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ~~~~~~/licensing~~~~~~
 */
package ru.entaxy.esb.platform.runtime.core.initializer.connection;

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

import ru.entaxy.esb.platform.runtime.core.initializer.api.AbstractInitializer;
import ru.entaxy.esb.platform.runtime.core.initializer.api.InitializerException;
import ru.entaxy.esb.platform.runtime.core.management.connection.util.ConnectionManagerUtil;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.charset.Charset;

public class ConnectionInitializer extends AbstractInitializer {

    private static final Logger log = LoggerFactory.getLogger(ConnectionInitializer.class);
    
    private static final String JSON_FILE_NAME = "entaxy-platform-connections.json";
    
    private static final String jsonBundlePath = "/connection/" + JSON_FILE_NAME;
    
    private static final String JSON_FILE_PATH = System.getProperty("karaf.etc") 
    		+ File.separator
    		+ "init"
    		+ File.separator
    		+ JSON_FILE_NAME;

    @Override
    public void init() throws InitializerException {
        log.info("ConnectionInitializer started");
        log.info("-->> " + JSON_FILE_PATH);
        
        try {
            initPlatformConnections(bundleContext);
        } catch (Exception e) {
            throw new InitializerException(this, "Can't create platform connections", "", e);
        }
    }

    @Override
    public void reinit() throws InitializerException {
    	// TODO Auto-generated method stub
    }
    
    private void initPlatformConnections(BundleContext bundleContext) throws Exception {
        String json = getJsonAsString(bundleContext);
        ConnectionManagerUtil.getService().createAndInstallConnections(json);
    }

    private String getJsonAsString(BundleContext context) throws IOException {
    	URL jsonUrl;
    	File f = new File(JSON_FILE_PATH);
    	if (f.exists() && f.canRead()) {
    		jsonUrl = f.toURI().toURL();
    		log.info("Path to json file: " + jsonUrl.toString());
    	} else {
	        jsonUrl = context.getBundle().getEntry(jsonBundlePath);
	        log.debug("Path to json file: " + jsonUrl.toString());
    	}
        InputStream inputStream = jsonUrl.openStream();
        byte[] bytes = inputStream.readAllBytes();
        String result = new String(bytes, Charset.defaultCharset());
        inputStream.close();
        return result;
    }

}
