/*-
 * ~~~~~~licensing~~~~~~
 * application-shell
 * ==========
 * 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.integration.applications.shell.application;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.Optional;

import org.apache.karaf.shell.api.action.Argument;
import org.apache.karaf.shell.api.action.Command;
import org.apache.karaf.shell.api.action.Option;
import org.apache.karaf.shell.api.action.lifecycle.Service;

import ru.entaxy.platform.base.support.karaf.shell.ShellTableFixed;
import ru.entaxy.platform.integration.applications.ApplicationItem;
import ru.entaxy.platform.integration.applications.EntaxyApplication;
import ru.entaxy.platform.integration.applications.EntaxyApplication.ITEM_TYPE;
import ru.entaxy.platform.integration.applications.EntaxyApplicationRevision;
import ru.entaxy.platform.integration.applications.EntaxyApplicationVersion;
import ru.entaxy.platform.integration.applications.shell.ApplicationShell;
import ru.entaxy.platform.config.runtime.ObjectConfigEditor;
import ru.entaxy.platform.config.runtime.ObjectConfigEditor.ConfigProperty;

@Service
@Command(name = "app-revision-config-print", scope = ApplicationShell.COMMAND_SCOPE)
public class ConfigPrintCommand extends RevisionSupport {

    @Argument(required = true)
    String configId;

    @Option(name = "-s", aliases = {"--show-system-properties"})
    boolean showSystemProperties = false;

    @Override
    protected void doExecute(EntaxyApplication application, EntaxyApplicationVersion version,
            EntaxyApplicationRevision revision) {

        Optional<ApplicationItem> configItemOpt = revision.getItems().stream()
                .filter(item -> item.getType().equals(ITEM_TYPE.CONFIG) && configId.equals(item.getId())).findFirst();
        if (configItemOpt.isEmpty()) {
            // output error
            System.err.println("ERROR: config [" + configId + "] not found");
            return;
        }

        ApplicationItem configItem = configItemOpt.get();

        File tempFile = null;

        try {
            Path temp = Files.createTempFile(configId, null);
            tempFile = temp.toFile().getAbsoluteFile();
            tempFile.getParentFile().mkdirs();
        } catch (IOException e) {
            // output error
            System.err.println("ERROR: can't create temp file, see exception below:\n");
            e.printStackTrace();
            return;
        }

        try (InputStream is = configItem.getInputStream()) {
            Files.copy(is, tempFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            // output error
            System.err.println("ERROR: can't write to temp file, see exception below:\n");
            e.printStackTrace();
            return;
        }

        ObjectConfigEditor editor = null;

        try {
            editor = ObjectConfigEditor.create(tempFile);
        } catch (IOException e) {
            System.err.println("ERROR: can't create config editor, see exception below:\n");
            e.printStackTrace();
            return;
        }

        try {
            editor.loadCurrent(configItem.getId());
        } catch (Exception e) {
            System.err.println("WARN: can't create config editor, see exception below:\n");
            e.printStackTrace();
        }

        ShellTableFixed table = new ShellTableFixed();
        table.column("Name");
        table.column("Display Name");
        table.column("Is system");
        table.column("Type");
        table.column("Value");
        table.column("Current Value");

        for (String name : editor.getPropertiesNames()) {
            ConfigProperty property = editor.getAsConfigProperty(name);
            if (property.hint.isInternal() && !showSystemProperties)
                continue;
            table.addRow().addContent(
                    name,
                    property.hint.getDisplayName(),
                    property.hint.isInternal(),
                    property.hint.getType(),
                    property.configValue == null ? "" : property.configValue.toString(),
                    property.currentValue == null ? "" : property.currentValue.toString());

        }

        table.print(System.out);
    }

}
