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

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.google.gson.JsonObject;

import ru.entaxy.platform.core.producer.executor.objectmodel.FactoredObject;
import ru.entaxy.platform.core.producer.executor.objectmodel.FactoredObjectProxy;
import ru.entaxy.platform.core.producer.executor.objectmodel.FactoredObjectRef;
import ru.entaxy.platform.core.producer.executor.objectmodel.ObjectModel;

public class GenerationModel {

    public static final String DIRECTIVE_SKIP_MERGE = "@SKIP_MERGE";

    public static final String DIRECTIVE_PUBLISH_URESOLVED = "@PUBLISH_UNRESOLVED";

    public static final String PUBLISH_UNRESOLVED_REF = "ref";
    public static final String PUBLISH_UNRESOLVED_OBJECT = "object";

    public static final String UNRESOLVED_CONTAINER_NAME = "##_UNRESOLVED";

    protected ObjectModel objectModel;

    protected List<AbstractTask> tasks = new LinkedList<>();

    public Map<Object, List<AbstractTask>> objectToTasksMap = new HashMap<>();

    public GeneratedObjectsPublishDataStorage publishDataStorage = new GeneratedObjectsPublishDataStorage();

    public GenerationModel(ObjectModel objectModel) {
        this.objectModel = objectModel;
    }

    public void load() {
        for (FactoredObject fo : objectModel.objects)
            if (!fo.isEmbedded())
                tasks.addAll(generateTasksForObject(fo, null, null));
        for (AbstractTask at : tasks)
            at.setGenerationModel(this);
    }

    protected List<AbstractTask> generateTasksForObject(FactoredObject fo, FactoredObjectRef originRef,
            FactoredObject originObject) {

        if (fo instanceof FactoredObjectProxy)
            return Collections.singletonList(new ResolveObjectTask((FactoredObjectProxy) fo));

        List<AbstractTask> localPreTasks = new LinkedList<>();
        List<AbstractTask> localPostTasks = new LinkedList<>();

        // first process embedded objects

        List<FactoredObject> embedded = fo.embedded.stream().filter(f -> (f instanceof FactoredObject))
                .map(f -> (FactoredObject) f)
                .collect(Collectors.toList());
        for (FactoredObject embeddedObject : embedded) {
            List<AbstractTask> tasksForEmbedded = generateTasksForObject(embeddedObject, null, fo);
            localPreTasks.addAll(tasksForEmbedded);
        }

        // process links to externalized embedded objects

        List<FactoredObjectRef> embeddedLinks = fo.embedded.stream().filter(f -> (f instanceof FactoredObjectRef))
                .map(f -> (FactoredObjectRef) f)
                .filter(f -> !f.isBackRef())
                .filter(f -> f.isLink())
                .collect(Collectors.toList());
        for (FactoredObjectRef embeddedRef : embeddedLinks) {
            FactoredObject embeddedObject = embeddedRef.getTargetObject();
            List<AbstractTask> tasksForEmbedded = generateTasksForObject(embeddedObject, embeddedRef, fo);

            // check the dependencies:
            // if embedded depends on main
            // then it must be generates after the main

            List<FactoredObjectRef> refs = objectModel.refs.stream()
                    .filter(r -> r.isDefinedIn(embeddedObject))
                    .filter(r -> fo.equals(r.getTargetObject()))
                    .collect(Collectors.toList());
            if (refs.isEmpty())
                localPreTasks.addAll(tasksForEmbedded);
            else
                localPostTasks.addAll(tasksForEmbedded);
        }

        // process embedded refs

        List<FactoredObjectRef> embeddedRefs = fo.embedded.stream().filter(f -> (f instanceof FactoredObjectRef))
                .map(f -> (FactoredObjectRef) f)
                .filter(f -> !f.isBackRef())
                .filter(f -> !f.isLink() || f.isResolveAlways())
                .collect(Collectors.toList());
        for (FactoredObjectRef embeddedRef : embeddedRefs) {

            if (!embeddedRef.isLink() || embeddedRef.isResolveAlways()) {
                localPreTasks.add(new ResolveRefTask(embeddedRef));
                if (!embeddedRef.isLink())
                    if (!embeddedRef.isRefByValueOnly())
                        localPreTasks.add(new GenerateRefTask(embeddedRef));
            }
        }

        List<AbstractTask> currentTasks = new ArrayList<>(localPreTasks);

        if (CalculateTask.hasCalculations(fo))
            currentTasks.add(new CalculateTask(fo));

        GenerateTask generateTask = new GenerateTask(fo);
        generateTask.originRef = originRef;
        generateTask.originObject = originObject;

        currentTasks.add(generateTask);

        for (AbstractTask at : localPreTasks)
            if (!at.isToMerge())
                if ((at instanceof GenerateTask) && checkDoMerge((GenerateTask) at)) {
                    currentTasks.add(new MergeTask(at, generateTask));
                } else if (at instanceof GenerateRefTask)
                    currentTasks.add(new MergeTask(at, generateTask));

        currentTasks.addAll(localPostTasks);

        for (AbstractTask at : localPostTasks)
            if (!at.isToMerge())
                if ((at instanceof GenerateTask) && checkDoMerge((GenerateTask) at)) {
                    currentTasks.add(new MergeTask(at, generateTask));
                } else if (at instanceof GenerateRefTask)
                    currentTasks.add(new MergeTask(at, generateTask));

        return currentTasks;
    }

    protected boolean checkDoMerge(GenerateTask generateTask) {
        if (generateTask.originRef == null)
            return true;
        JsonObject jo = generateTask.originRef.origin;

        if (!jo.has(DIRECTIVE_SKIP_MERGE))
            return true;

        try {
            return !jo.get(DIRECTIVE_SKIP_MERGE).getAsBoolean();
        } catch (Exception ignore) {
            return true;
        }

    }

    public List<AbstractTask> getTasks() {
        return tasks;
    }

}
