/*-
 * ~~~~~~licensing~~~~~~
 * test-producers
 * ==========
 * 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.producer.executor.objectmodel;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;
import java.util.stream.Collectors;

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

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

import ru.entaxy.platform.base.support.CommonUtils;
import ru.entaxy.platform.base.support.DependencySorter;
import ru.entaxy.platform.base.support.JSONUtils;
import ru.entaxy.platform.base.support.JSONUtils.JsonTraverse;

public class ObjectModel {

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

    public List<FactoredObject> objects = new ArrayList<>();

    public List<FactoredObjectRef> refs = new ArrayList<>();

    protected Object rootObject = null;
    protected JsonObject jsonCurrent = null;
    protected JsonObject jsonOrigin = null;

    protected boolean isDirty = false;
    protected boolean isTracked = false;

    public void addObject(FactoredObject factoredObject) {
        this.objects.add(factoredObject);
    }

    public void addRef(FactoredObjectRef factoredObjectRef) {
        this.refs.add(factoredObjectRef);
    }

    public Object load(JsonElement root) {

        if (!root.isJsonObject()) {
            log.debug("NOT AN OBJECT!!");
            return null;
        }

        jsonCurrent = root.getAsJsonObject();
        jsonOrigin = jsonCurrent.deepCopy();

        JsonTraverse jsonTraverse = (new JsonTraverse()).checker(new FactoryChecker(this));

        rootObject = jsonTraverse.traverse(jsonCurrent);
        return rootObject;
    }

    public void checkRefs() {
        List<FactoredObjectRef> originRefs = this.refs.stream()
                .filter(r -> (r.getTargetObject() == null))
                .collect(Collectors.toList());
        for (FactoredObjectRef ref : originRefs) {
            String targetId = ref.getTargetId();
            String targetUuid = ref.getTargetUuid();
            List<FactoredObject> fos = this.objects.stream()
                    .filter(fo -> (fo.getObjectId().equals(targetId)) || fo.getUuid().equals(targetUuid))
                    .collect(Collectors.toList());
            if (fos.isEmpty()) {

                // System.out.println("CREATING PROXY FOR [" + targetId + "]");

                // create proxy
                FactoredObjectProxy proxy = new FactoredObjectProxy(this);
                proxy.wrap(FactoredObjectProxy.getDefaultOrigin(), new HashMap<>(), "");
                proxy.setObjectId(ref.getTargetId());
                proxy.setObjectType(ref.getTargetType());

                // update ref
                ref.setExternal(true);
                ref.setTargetObject(proxy);

            } else {

                // update objectType for proxy
                if (fos.get(0) instanceof FactoredObjectProxy) {
                    if (!CommonUtils.isValid(fos.get(0).getObjectType()))
                        fos.get(0).setObjectType(ref.getTargetType());
                }

                ref.setExternal(fos.get(0) instanceof FactoredObjectProxy);
                ref.setTargetObject(fos.get(0));
            }
        }
    }

    public void layout() throws Exception {

        JsonObject effectiveJson = new JsonObject();

        // collect root objects
        List<FactoredObject> rootObjects =
                this.objects.stream().filter(fo -> fo.definedIn == null).collect(Collectors.toList());
        JsonArray roots = new JsonArray();
        for (FactoredObject fo : rootObjects)
            roots.add(fo.origin);

        List<FactoredObject> newRoots = new ArrayList<>();
        List<JsonElement> movedElements = new ArrayList<>();
        for (FactoredObject fo : rootObjects)
            movedElements.addAll(layoutObject(fo, newRoots));

        rootObjects.addAll(newRoots);
        for (JsonElement je : movedElements)
            roots.add(je);

        embedReferences();

        for (FactoredObject fo : objects) {
            List<FactoredObjectRef> objrefs = refs.stream()
                    .filter(r -> r.isDefinedIn(fo))
                    .filter(r -> !fo.equals(r.getTargetObject()))
                    .collect(Collectors.toList());
        }

        List<FactoredObject> sortedRootObjects = DependencySorter.getSortedList(
                rootObjects,
                new DependencySorter.DependencyProvider<FactoredObject>() {

                    @Override
                    public List<FactoredObject> getDependencies(FactoredObject inspectedObject) {

                        // calculate dependencies based on refs
                        List<FactoredObject> dependencies =
                                refs.stream().filter(ref -> ref.isDefinedIn(inspectedObject))
                                        .filter(ref -> !ref.isBackRef())
                                        .filter(ref -> !ref.isLink())
                                        // .filter(ref->!ref.isExternal())
                                        .filter(ref -> !inspectedObject.equals(ref.getTargetObject()))
                                        .map(ref -> ref.getTargetObject())
                                        .collect(Collectors.toList());

                        // calculate transitive dependencies based on refs in embedded objects
                        List<FactoredObject> embedded = inspectedObject.embedded.stream()
                                .filter(obj -> obj instanceof FactoredObjectRef)
                                .map(obj -> (FactoredObjectRef) obj)
                                .filter(ref -> ref.isLink())
                                .map(ref -> ref.getTargetObject())
                                .collect(Collectors.toList());

                        for (FactoredObject inspectedEmbedded : embedded) {
                            List<FactoredObject> transitives =
                                    refs.stream().filter(ref -> ref.isDefinedIn(inspectedEmbedded))
                                            .filter(ref -> !ref.isBackRef())
                                            .filter(ref -> !ref.isLink())
                                            // .filter(ref->!ref.isExternal())
                                            .filter(ref -> !inspectedObject.equals(ref.getTargetObject()))
                                            .filter(ref -> !inspectedEmbedded.equals(ref.getTargetObject()))
                                            .map(ref -> ref.getTargetObject())
                                            .collect(Collectors.toList());
                            for (FactoredObject t : transitives)
                                if (!dependencies.contains(t))
                                    dependencies.add(t);
                        }

                        return dependencies;
                    }

                });


/*				new LinkedList<>(rootObjects);
		Collections.<FactoredObject>sort(sortedRootObjects, new Comparator<FactoredObject>() {

			@Override
			public int compare(FactoredObject o1, FactoredObject o2) {
				if (o1.dependsOn.contains(o2))
					return 1;
				if (o2.dependsOn.contains(o1))
					return -1;
				return o1.dependsOn.size() - o2.dependsOn.size();
			}
		});
*/

        this.objects = sortedRootObjects;

        JsonArray sortedRoots = new JsonArray();
        for (FactoredObject fo : sortedRootObjects)
            sortedRoots.add(fo.origin);


        // and finalize json
        effectiveJson.add("##objects", sortedRoots);
        jsonCurrent = effectiveJson;
        log.debug(effectiveJson.toString());
    }

    protected void embedReferences() {
        for (FactoredObjectRef ref : refs) {

            FactoredObject fo = ref.definedIn;
            /*			if ("private".equals(ref.scope))
            				while ((fo!=null) && "private".equals(fo.scope))
            					fo = fo.definedIn;
            */
            if (fo == null) {
                log.debug("Error: orphaned ref: [" + ref.getTargetId() + "]");
                continue;
            }
            fo.embed(ref);
        }
    }

    protected List<JsonElement> layoutObject(FactoredObject factoredObject, List<FactoredObject> rootObjects) {

        List<JsonElement> result = new ArrayList<>();

        for (FactoredObject fo : factoredObject.dependsOn) {

            if ("private".equals(fo.scope) && !fo.isEmbedded()) {
                log.debug("FOUND PRIVATE OBJECT :: " + fo.getObjectId());
                fo.setEmbedded(true);
                log.debug("CREATING REF TO :: " + fo.getObjectId());
                FactoredObjectRef objectRef = new FactoredObjectRef(this, fo);
                objectRef.setLink(true);
                objectRef.setAutoGenerated(true);
                /* FactoredObject owner = fo.definedIn;
                // find first non-private object
                while ((owner!=null) && "private".equals(owner.scope))
                	owner = owner.definedIn;
                if (owner == null) {
                	log.debug("Error: orphaned private object: [" + fo.getObjectId() + "]");
                	continue;
                } */
                result.add(fo.origin);

                if (fo.origin.has("refConfig") && fo.origin.get("refConfig").isJsonObject()) {
                    JsonObject refConfig = fo.origin.get("refConfig").getAsJsonObject();
                    for (Entry<String, JsonElement> entry : refConfig.entrySet()) {
                        if (objectRef.origin.has(entry.getKey()))
                            objectRef.origin.remove(entry.getKey());
                        objectRef.origin.add(entry.getKey(), entry.getValue().deepCopy());
                    }
                    objectRef.updateFromOrigin();
                }

                objectRef.setTraverseMap(JSONUtils.element2map(objectRef.origin), null);

                log.debug("REPLACING :: " + fo.getObjectId());
                JSONUtils.replaceValue(factoredObject.origin, fo.relativePath, objectRef.origin);
                log.debug("TOTAL REFS :: " + refs.size());
                rootObjects.add(fo);
                // owner.embed(objectRef);
                result.addAll(layoutObject(fo, rootObjects));
            } else {
                FactoredObjectRef objectRef = new FactoredObjectRef(this, fo);
                objectRef.setAutoGenerated(true);
                result.add(fo.origin);

                // keep definedIn attribute in ref
                if (fo.definedIn == factoredObject) {
                    if (objectRef.origin.has(FactoredObjectRef.IS_DEFINITION_ORIGIN))
                        objectRef.origin.remove(FactoredObjectRef.IS_DEFINITION_ORIGIN);
                    objectRef.origin.addProperty(FactoredObjectRef.IS_DEFINITION_ORIGIN, true);
                } else {
                    objectRef.origin.remove(FactoredObjectRef.IS_DEFINITION_ORIGIN);
                }

                if (fo.origin.has("refConfig") && fo.origin.get("refConfig").isJsonObject()) {
                    JsonObject refConfig = fo.origin.get("refConfig").getAsJsonObject();
                    for (Entry<String, JsonElement> entry : refConfig.entrySet()) {
                        if (objectRef.origin.has(entry.getKey()))
                            objectRef.origin.remove(entry.getKey());
                        objectRef.origin.add(entry.getKey(), entry.getValue().deepCopy());
                    }
                    objectRef.updateFromOrigin();
                }
                objectRef.setTraverseMap(JSONUtils.element2map(objectRef.origin), null);

                JSONUtils.replaceValue(factoredObject.origin, fo.relativePath, objectRef.origin);
                rootObjects.add(fo);
                result.addAll(layoutObject(fo, rootObjects));
            }

        }

        return result;

    }

    public JsonObject getJsonCurrent() {
        return jsonCurrent;
    }

    public JsonObject getJsonOrigin() {
        return jsonOrigin;
    }

    public Object getRootObject() {
        return rootObject;
    }

    public void startTracking() {
        this.isTracked = true;
    }

    public boolean stopTracking() {
        this.isTracked = false;
        boolean result = this.isDirty;
        this.isDirty = false;
        return result;
    }

    public void setDirty() {
        if (this.isTracked)
            this.isDirty = true;
    }

    public boolean isDirty() {
        return isDirty;
    }


}
