/*-
 * ~~~~~~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.io.OutputStreamWriter;
import java.io.PrintStream;
import java.lang.reflect.Field;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.felix.gogo.runtime.threadio.ThreadPrintStream;
import org.apache.felix.service.command.Job;
import org.jline.terminal.Terminal;

public class ShellTableExt {

    private static final char SEP_HORIZONTAL = '─';
    private static final char SEP_VERTICAL = '│';
    private static final char SEP_CROSS = '┼';

    private static final char SEP_HORIZONTAL_ASCII = '-';
    private static final char SEP_VERTICAL_ASCII = '|';
    private static final char SEP_CROSS_ASCII = '+';

    private static final String DEFAULT_SEPARATOR = " " + SEP_VERTICAL + " ";
    private static final String DEFAULT_SEPARATOR_ASCII = " " + SEP_VERTICAL_ASCII + " ";
    private static final String DEFAULT_SEPARATOR_NO_FORMAT = "\t";

    private List<ColExt> cols = new ArrayList<>();
    private List<RowExt> rows = new ArrayList<>();
    private boolean showHeaders = true;
    private String separator = DEFAULT_SEPARATOR;
    private int size;
    private String emptyTableText;
    private boolean forceAscii;

    private boolean splitLists = false;

    public ShellTableExt() {

    }

    public ShellTableExt noHeaders() {
        this.showHeaders = false;
        return this;
    }

    public ShellTableExt separator(String separator) {
        this.separator = separator;
        return this;
    }

    public ShellTableExt size(int size) {
        this.size = size;
        return this;
    }

    public boolean isSplitLists() {
        return splitLists;
    }

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

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

    public ShellTableExt column(ColExt colunmn) {
        cols.add(colunmn);
        colunmn.ownerTable = this;
        return this;
    }

    public ColExt column(String header) {
        ColExt col = new ColExt(header);
        col.ownerTable = this;
        cols.add(col);
        return col;
    }

    public RowExt addRow() {
        RowExt row = new RowExt();
        rows.add(row);
        return row;
    }

    public RowExt addRow(Object dataObject) {
        RowExt row = addRow();
        row.setDataObject(dataObject);
        return row;
    }

    public ShellTableExt forceAscii() {
        forceAscii = true;
        return this;
    }

    /**
     * Set text to display if there are no rows in the table.
     *
     * @param text the text to display when the table is empty.
     * @return the shell table.
     */
    public ShellTableExt emptyTableText(String text) {
        this.emptyTableText = text;
        return this;
    }

    public void print(PrintStream out) {
        print(out, true);
    }

    public void print(PrintStream out, boolean format) {
        print(out, null, format);
    }

    public void print(PrintStream out, Charset charset, boolean format) {
        boolean unicode = supportsUnicode(out, charset);
        String separator = unicode ? this.separator : DEFAULT_SEPARATOR_ASCII;

        // "normal" table rendering, with borders
        RowExt headerRow = new RowExt(cols);
        headerRow.formatContent(cols);
        for (RowExt row : rows) {
            row.formatContent(cols);
        }

        if (size > 0) {
            adjustSize();
        }

        if (format && showHeaders) {
            String headerLine = headerRow.getContent(cols, separator);
            out.println(headerLine);
            int iCol = 0;
            for (ColExt col : cols) {
                if (iCol++ == 0) {
                    out.print(underline(col.getSize(), false, unicode));
                } else {
                    out.print(underline(col.getSize() + 3, true, unicode));
                }
                iCol++;
            }
            out.println();
        }

        for (RowExt row : rows) {
            if (!format) {
                if (separator == null || separator.equals(DEFAULT_SEPARATOR))
                    out.println(row.getContent(cols, DEFAULT_SEPARATOR_NO_FORMAT));
                else
                    out.println(row.getContent(cols, separator));
            } else {
                out.println(row.getContent(cols, separator));
            }
        }

        if (format && rows.size() == 0 && emptyTableText != null) {
            out.println(emptyTableText);
        }
    }

    private boolean supportsUnicode(PrintStream out, Charset charset) {
        if (forceAscii) {
            return false;
        }
        if (charset == null) {
            charset = getEncoding(out);
        }
        if (charset == null) {
            return false;
        }
        CharsetEncoder encoder = charset.newEncoder();
        return encoder.canEncode(separator)
                && encoder.canEncode(SEP_HORIZONTAL)
                && encoder.canEncode(SEP_CROSS);
    }

    private Charset getEncoding(PrintStream ps) {
        if (ps.getClass() == ThreadPrintStream.class) {
            try {
                return ((Terminal) Job.Utils.current().session().get(".jline.terminal")).encoding();
            } catch (Throwable t) {
                // ignore
            }
            try {
                ps = (PrintStream) ps.getClass().getMethod("getCurrent").invoke(ps);
            } catch (Throwable t) {
                // ignore
            }
        }
        try {
            Field f = ps.getClass().getDeclaredField("charOut");
            f.setAccessible(true);
            OutputStreamWriter osw = (OutputStreamWriter) f.get(ps);
            return Charset.forName(osw.getEncoding());
        } catch (Throwable t) {
            // ignore
        }
        return null;
    }

    private void adjustSize() {
        int currentSize = 0;
        for (ColExt col : cols) {
            currentSize += col.size + separator.length();
        }
        currentSize -= separator.length();
        int sizeToGrow = size - currentSize;

        for (int i = cols.size() - 1; i >= 0; i--) {
            ColExt col = cols.get(i);
            if (col.maxSize == -1) {
                col.size = Math.max(0, col.size + sizeToGrow);
                return;
            }
        }

    }

    private String underline(int length, boolean crossAtBeg, boolean supported) {
        char[] exmarks = new char[length];
        Arrays.fill(exmarks, supported ? SEP_HORIZONTAL : SEP_HORIZONTAL_ASCII);
        if (crossAtBeg) {
            exmarks[1] = supported ? SEP_CROSS : SEP_CROSS_ASCII;
        }
        return new String(exmarks);
    }

    public static class CellData {
        public Object dataObject;
        public String cellContent;

        public CellData(Object dataObject, String cellContent) {
            this.dataObject = dataObject;
            this.cellContent = cellContent;
        }

    }

}
