/*-
 * ~~~~~~licensing~~~~~~
 * artifact-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.platform.core.artifact.installer.builder.impl;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ru.entaxy.platform.core.artifact.DeployedArtifact;
import ru.entaxy.platform.core.artifact.installer.builder.InstallationResult;
import ru.entaxy.platform.core.artifact.installer.builder.Installer;
import ru.entaxy.platform.core.artifact.installer.builder.typed.BundleInstaller;
import ru.entaxy.platform.core.artifact.installer.builder.typed.DefaultTypedInstallerFactory;
import ru.entaxy.platform.core.artifact.installer.builder.typed.TypedInstaller;
import ru.entaxy.platform.core.artifact.installer.builder.typed.TypedInstallerManager;
import ru.entaxy.platform.core.artifact.installer.builder.typed.impl.HelperCreator;
import ru.entaxy.platform.core.artifact.installer.builder.typed.impl.TypedInstallerHelperAware;
import ru.entaxy.platform.core.artifact.installer.builder.typed.impl.TypedInstallerHelperImpl;
import ru.entaxy.platform.core.artifact.installer.builder.typed.impl.TypedInstallerImpl;
import ru.entaxy.platform.core.artifact.legacy.BundleController;

public abstract class AbstractInstaller<T extends Installer<T>, H extends TypedInstallerHelperImpl>
        implements BundleController {

    private static final Logger log = LoggerFactory.getLogger(AbstractInstaller.class);

    static {
        TypedInstallerManager.register(DefaultTypedInstallerFactory.getInstance());
    }

    protected DeployedArtifact artifact = null;
    protected String sourceLocation = null;
    protected String bundleName = null;

    // protected Map<String, Class<? extends TypedInstallerImpl>> typedInstallerClasses = new
    // HashMap<>();
    protected Map<Class<? extends TypedInstaller>, Class<? extends H>> typedHelperClasses = new HashMap<>();


    // for BundleInstaller implementation
    protected BundleInstaller bundleInstaller = null;

    protected TypedInstaller typedInstaller = null;

    protected AbstractInstaller() {
        // this.typedInstallerClasses = new HashMap<>();
        this.typedHelperClasses = new HashMap<>();
    }

    protected abstract Class<H> getHelperClass();

    protected void doCreateTypedInstaller(Class<? extends TypedInstallerImpl> clazz) {
        Constructor<?> constructor;
        try {
            constructor = clazz.getConstructor();
            this.typedInstaller = (TypedInstallerImpl) constructor.newInstance();
        } catch (NoSuchMethodException | SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InstantiationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    protected void createTypedInstaller() {
        if (artifact == null || artifact.getArtifact() == null)
            return;
        this.typedInstaller = TypedInstallerManager.create(this, artifact.getArtifact().getCategory());
        if (this.typedInstaller != null) {
            initTypedInstaller();
        }
    }

/*
protected void createTypedInstaller() {
Class<? extends TypedInstallerImpl> clazz =
artifact == null
? null
: typedInstallerClasses.get(artifact.getArtifact().getCategory());
if (clazz == null)
// TODO throw exception
return;
doCreateTypedInstaller(clazz);
if (this.typedInstaller != null) {
initTypedInstaller();
}
}
*/
    protected void findTypedInstaller(Class<? extends TypedInstaller> type) {
        this.typedInstaller = TypedInstallerManager.create(this, type);
        if (this.typedInstaller != null) {
            initTypedInstaller();
        }
    }

/*    
protected void findTypedInstaller(Class<?> type) {
Class<? extends TypedInstallerImpl> clazz = null;
for (Class<? extends TypedInstallerImpl> cl : typedInstallerClasses.values())
if ((cl != null) && type.isAssignableFrom(cl)) {
clazz = cl;
break;
}
if (clazz == null)
// TODO throw exception
return;
doCreateTypedInstaller(clazz);
if (this.typedInstaller != null) {
initTypedInstaller();
}
}
*/
    protected H createHelper() {
        Class<? extends H> clazz = typedHelperClasses.get(typedInstaller.getClass());
        if (clazz == null) {
            for (Class<? extends TypedInstaller> typedClass : typedHelperClasses.keySet())
                if (typedClass.isInstance(typedInstaller)) {
                    clazz = typedHelperClasses.get(typedClass);
                    break;
                }
        }
        if (clazz == null) {
            // check installer itself
            if (typedInstaller instanceof HelperCreator)
                return ((HelperCreator) typedInstaller).createHelper(getHelperClass());
        }
        if (clazz == null)
            return createDefaultHelper();
        Constructor<?> constructor;
        String errorMessage = "Error creating typed installer helper";
        try {
            constructor = clazz.getConstructor();
            return (H) constructor.newInstance();
        } catch (NoSuchMethodException | SecurityException e) {
            log.error(errorMessage, e);
        } catch (InstantiationException e) {
            log.error(errorMessage, e);
        } catch (IllegalAccessException e) {
            log.error(errorMessage, e);
        } catch (IllegalArgumentException e) {
            log.error(errorMessage, e);
        } catch (InvocationTargetException e) {
            log.error(errorMessage, e);
        }

        return createDefaultHelper();
    }

    protected abstract H createDefaultHelper();

    protected void refreshTypedInstaller() {
        this.typedInstaller.clearInstaller();
        this.typedInstaller.setArtifact(this.artifact);
        this.typedInstaller.setSourceLocation(this.sourceLocation);
        this.typedInstaller.setTypedName(this.bundleName);
    }

    protected void initTypedInstaller() {
        refreshTypedInstaller();

        H helper = createHelper();
        initHelper(helper);
        if (this.typedInstaller instanceof TypedInstallerHelperAware)
            ((TypedInstallerHelperAware) this.typedInstaller).setHelper(helper);
    }

    protected void initHelper(H helper) {

    };

    public <S extends TypedInstaller> S typed(Class<S> type) {
        if (this.typedInstaller == null)
            createTypedInstaller();
        if (this.typedInstaller == null)
            findTypedInstaller(type);
        if (this.typedInstaller == null)
            // TODO throw exception
            return null;
        if (!type.isAssignableFrom(this.typedInstaller.getClass()))
            // TODO throw exception
            return null;
        return type.cast(this.typedInstaller);
    }

    public InstallationResult install() {
        if (typedInstaller == null) {
            createTypedInstaller();
        }
        if (typedInstaller != null)
            return typedInstaller.install();
        return null;
    }

    public InstallationResult uninstall() {
        if (typedInstaller == null) {
            createTypedInstaller();
        }
        if (typedInstaller != null)
            return typedInstaller.uninstall();
        return null;
    }

    public T artifact(DeployedArtifact artifact) {
        setArtifact(artifact);
        return (T) this;
    }

    public T sourceLocation(String sourceLocation) {
        setSourceLocation(sourceLocation);
        return (T) this;
    }

    public void setArtifact(DeployedArtifact artifact) {
        this.artifact = artifact;
    }

    public void setSourceLocation(String sourceLocation) {
        this.sourceLocation = sourceLocation;
    }

    public T bundleName(String bundleName) {
        setBundleName(bundleName);
        return (T) this;
    }

    public void setBundleName(String bundleName) {
        this.bundleName = bundleName;
    }

    public BundleController bundleController() {
        return (BundleController) this;
    }

    protected BundleInstaller createBundleInstaller() {
        return typed(BundleInstaller.class);
    }

    protected void initBundleInstaller() {
        if (this.bundleInstaller == null)
            this.bundleInstaller = createBundleInstaller();
    }

    protected void clear() {
        this.artifact = null;
        this.sourceLocation = null;
        this.bundleName = null;
    }

    /*
     * BundleController implementation
     */

    public String installAndStartBundle(String bundleUrl, String bundleName) throws Exception {
        initBundleInstaller();
        clear();
        this.sourceLocation(bundleUrl);
        refreshTypedInstaller();
        InstallationResult result = this.bundleInstaller.update(bundleName).installOnlyIfMissing().start().install();
        return result.getProperties()
                .getOrDefault(InstallationResult.PROP_BUNDLE_STATUS, "RESOLVED")
                .toString();
    };

    public void installBundle(String bundleUrl) throws Exception {
        initBundleInstaller();
        clear();
        this.sourceLocation(bundleUrl);
        refreshTypedInstaller();
        this.bundleInstaller.update().installOnlyIfMissing().install();
    };

    public String updateBundle(String bundleName) throws Exception {
        initBundleInstaller();
        clear();
        InstallationResult result = this.bundleInstaller.update(bundleName).updateOnly().install();
        return result.getProperties()
                .getOrDefault(InstallationResult.PROP_BUNDLE_STATUS, "Resolved")
                .toString();
    };

    public String startBundle(String bundleName) throws Exception {
        initBundleInstaller();
        clear();
        bundleName(bundleName);
        refreshTypedInstaller();
        InstallationResult result = this.bundleInstaller.startOnly().install();
        return result.getProperties().getOrDefault(InstallationResult.PROP_BUNDLE_STATUS, "Resolved").toString();
    };

    public String stopBundle(String bundleName) throws Exception {
        initBundleInstaller();
        clear();
        bundleName(bundleName);
        refreshTypedInstaller();
        InstallationResult result = this.bundleInstaller.stopOnly().install();
        return result.getProperties().getOrDefault(InstallationResult.PROP_BUNDLE_STATUS, "Resolved").toString();
    };

    public void uninstallBundle(String bundleName) throws Exception {
        initBundleInstaller();
        clear();
        bundleName(bundleName);
        refreshTypedInstaller();
        this.bundleInstaller.uninstall();
    };

}
