/*-
 * ~~~~~~licensing~~~~~~
 * base-support
 * ==========
 * 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~~~~~~
 */
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
 * agreements. See the NOTICE file distributed with this work for additional information regarding
 * copyright ownership. The ASF licenses this file to You 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.
 */
package ru.entaxy.platform.base.support.karaf.shell;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import org.apache.karaf.shell.support.ansi.SimpleAnsi;

/**
 * Column definition.
 */
public class ColExt {
    // This is kept here only for backwards compatibility
    // and is used in cyan(boolean) method
    private static final Function<String, String> COLOR_CYAN =
            (cellContent) -> SimpleAnsi.COLOR_CYAN;

    Function<String, String> colorProvider;

    Function<ShellTableExt.CellData, String> colorProviderExt;

    protected ShellTableExt ownerTable = null;

    /**
     * Column header.
     */
    private String header;

    /**
     * Maximum size of this column. The default -1 means the column may grow indefinitely
     */
    int maxSize = -1;

    int size = 0;

    boolean wrap;
    boolean bold;
    boolean cyan;

    Boolean splitLists = null;

    /**
     * Alignment
     */
    private HAlignExt align = HAlignExt.left;

    public ColExt(String header) {
        this.header = header;
    }

    public ColExt align(HAlignExt align) {
        this.align = align;
        return this;
    }

    public ColExt alignLeft() {
        this.align = HAlignExt.left;
        return this;
    }

    public ColExt alignRight() {
        this.align = HAlignExt.right;
        return this;
    }

    public ColExt alignCenter() {
        this.align = HAlignExt.center;
        return this;
    }

    public ColExt maxSize(int maxSize) {
        this.maxSize = maxSize;
        return this;
    }

    public ColExt splitLists() {
        return splitLists(true);
    }

    public ColExt splitLists(boolean value) {
        this.splitLists = value;
        return this;
    }

    public ColExt wrap() {
        return wrap(true);
    }

    public ColExt wrap(boolean wrap) {
        this.wrap = wrap;
        return this;
    }

    public ColExt bold() {
        return bold(true);
    }

    public ColExt bold(boolean bold) {
        this.bold = bold;
        return this;
    }

    public ColExt cyan() {
        return cyan(true);
    }

    public ColExt cyan(boolean cyan) {
        if (cyan)
            colorProvider(COLOR_CYAN);

        // Only remove colorProvider if argument is false and
        // member equals COLOR_CYAN
        else if (this.colorProvider == COLOR_CYAN)
            colorProvider(null);

        return this;
    }

    public int getSize() {
        return size;
    }

    public ColExt colorProvider(Function<String, String> colorProvider) {
        this.colorProvider = colorProvider;
        return this;
    }

    public ColExt colorProviderExt(Function<ShellTableExt.CellData, String> colorProvider) {
        this.colorProviderExt = colorProvider;
        return this;
    }

    protected void updateSize(int cellSize) {
        if (this.size <= cellSize) {
            this.size = getClippedSize(cellSize);
        }
    }

    private int getClippedSize(int cellSize) {
        return this.maxSize == -1 ? cellSize : Math.min(cellSize, this.maxSize);
    }

    /*
    String format(Object cellData) {
        if (cellData == null) {
            cellData = "";
        }
        String fullContent = String.format("%s", cellData);
        if (fullContent.length() == 0) {
            return "";
        }
        String finalContent = cut(fullContent, getClippedSize(fullContent.length()));
        updateSize(finalContent.length());
        return finalContent;
    }
    */

    protected boolean isSplitLists() {
        if (this.splitLists != null)
            return this.splitLists;
        if (ownerTable != null)
            return ownerTable.isSplitLists();
        return false;
    }

    /*
    @ENTAXY_FIX:
        when calculating cell size we must take into account not LENGTH, but WIDTH of the data
        'cause data may contain "\n" so the LENGTH of data won't be equal to it's WIDTH 
    */
    @SuppressWarnings("unchecked")
    public String format(Object cellData) {
        if (cellData == null) {
            cellData = "";
        }

        String fullContent = String.format("%s", cellData);

        if (isSplitLists() && (cellData instanceof List)) {
            fullContent = (String) ((List) cellData).stream().map(v -> v == null ? "" : v.toString())
                    .collect(Collectors.joining("\n"));
        }

        if (fullContent.length() == 0) {
            return "";
        }
        String finalContent = cut(fullContent, getClippedSize(fullContent.length()));

        int finalContentWidth = 0;
        for (String s : Arrays.asList(finalContent.split("\n")))
            finalContentWidth = Math.max(finalContentWidth, s.length());

        updateSize(finalContentWidth);
        return finalContent;
    }

    String getHeader() {
        return header;
    }

    String getContent(ShellTableExt.CellData cellData) {

        String content = cellData.cellContent;

        List<String> lines = new ArrayList<>();
        lines.addAll(Arrays.asList(content.split("\n")));
        if (wrap) {
            List<String> wrapped = new ArrayList<>();
            for (String line : lines) {
                wrapped.addAll(wrap(line));
            }
            lines = wrapped;
        }

        String color = null;
        if (colorProviderExt != null) {
            color = colorProviderExt.apply(cellData);
        } else if (colorProvider != null) {
            color = colorProvider.apply(content);
        }

        StringBuilder sb = new StringBuilder();
        for (String line : lines) {
            if (sb.length() > 0) {
                sb.append("\n");
            }
            line = this.align.position(cut(line, size), this.size);
            if (bold) {
                line = SimpleAnsi.INTENSITY_BOLD + line + SimpleAnsi.INTENSITY_NORMAL;
            }

            if (color != null)
                sb.append(color);

            sb.append(line);

            if (color != null)
                sb.append(SimpleAnsi.COLOR_DEFAULT);
        }
        return sb.toString();
    }

    @Deprecated
    String getContent(String content) {
        List<String> lines = new ArrayList<>();
        lines.addAll(Arrays.asList(content.split("\n")));
        if (wrap) {
            List<String> wrapped = new ArrayList<>();
            for (String line : lines) {
                wrapped.addAll(wrap(line));
            }
            lines = wrapped;
        }

        String color = null;
        if (colorProvider != null) {
            color = colorProvider.apply(content);
        }

        StringBuilder sb = new StringBuilder();
        for (String line : lines) {
            if (sb.length() > 0) {
                sb.append("\n");
            }
            line = this.align.position(cut(line, size), this.size);
            if (bold) {
                line = SimpleAnsi.INTENSITY_BOLD + line + SimpleAnsi.INTENSITY_NORMAL;
            }

            if (color != null)
                sb.append(color);

            sb.append(line);

            if (color != null)
                sb.append(SimpleAnsi.COLOR_DEFAULT);
        }
        return sb.toString();
    }

    /*
    protected String cut(String content, int size) {
        if (content.length() <= size) {
            return content;
        } else {
            return content.substring(0, Math.max(0, size - 1));
        }
    }
    */

    protected String cut0(String content, int size) {
        if (content.length() <= size) {
            return content;
        } else {
            return content.substring(0, Math.max(0, size - 1));
        }
    }

    protected String cut(String content, int size) {
        if (content.length() <= size) {
            return content;
        } else {

            String[] contentSplitted = content.split("\n");
            for (int i = 0; i < contentSplitted.length; i++)
                contentSplitted[i] = cut0(contentSplitted[i], size);

            if (contentSplitted.length == 1)
                return contentSplitted[0];

            return Arrays.asList(contentSplitted).stream().collect(Collectors.joining("\n"));
        }
    }

    protected List<String> wrap(String str) {
        List<String> result = new ArrayList<>();
        Pattern wrap = Pattern.compile("(\\S\\S{" + size + ",}|.{1," + size + "})(\\s+|$)");
        int cur = 0;
        while (cur >= 0) {
            int lst = str.indexOf('\n', cur);
            String s = (lst >= 0) ? str.substring(cur, lst) : str.substring(cur);
            if (s.length() == 0) {
                result.add(s);
            } else {
                Matcher m = wrap.matcher(s);
                while (m.find()) {
                    result.add(m.group());
                }
            }
            if (lst >= 0) {
                cur = lst + 1;
            } else {
                break;
            }
        }
        return result;
    }


}
