package com.printer.demo.bean;

import android.annotation.SuppressLint;
import android.util.Log;

import com.printer.sdk.utils.Utils;

import java.util.ArrayList;
import java.util.List;

@SuppressLint("UseSparseArrays")
public class AlignedTable {
    private static final String TAG = "AlignedTable";

    public enum Align {LEFT, CENTER, RIGHT}

    private final List<String> tableRows = new ArrayList<>();
    private final String tableReg;
    private final int[] tableColWidth;          // 单位：像素 或 汉字数
    private final Align[] columnAlignments;
    private final int rowSpacing;
    private final int colSpacing;
    private final boolean widthIsPixel;         // true=像素  false=汉字数

    /**
     * 新增构造：widthIsPixel = true 表示 columnWidth 是像素，否则按老逻辑（汉字数）
     */
    public AlignedTable(String column, String regularExpression, int[] columnWidth,
                        int rowSpacing, int colSpacing, boolean widthIsPixel) {
        this.widthIsPixel = widthIsPixel;
        if (column != null && !column.trim().isEmpty()) {
            tableRows.add(column);
        }
        this.tableReg = regularExpression;
        this.rowSpacing = rowSpacing;
        this.colSpacing = colSpacing;

        int colCount = column.split(regularExpression).length;
        this.tableColWidth = columnWidth != null ? columnWidth : new int[colCount];
        this.columnAlignments = new Align[colCount];
        for (int i = 0; i < colCount; i++) {
            this.columnAlignments[i] = Align.LEFT;
        }
    }

    /** 老接口：默认按汉字数 */
    public AlignedTable(String column, String regularExpression, int[] columnWidth,
                        int rowSpacing, int colSpacing) {
        this(column, regularExpression, columnWidth, rowSpacing, colSpacing, false);
    }

    public void setColumnAlign(int columnIndex, Align align) {
        if (columnIndex >= 0 && columnIndex < columnAlignments.length) {
            columnAlignments[columnIndex] = align;
        }
    }

    public void addRow(String row) {
        if (row != null) tableRows.add(row);
    }

    public String getTableText() {
        StringBuilder sb = new StringBuilder();
        for (String row : tableRows) {
            String[] cells = row.split(tableReg, -1);
            sb.append(printTableLine(cells));
            for (int i = 0; i < rowSpacing; i++) sb.append('\n');
        }
        return sb.toString();
    }

    private String printTableLine(String[] cells) {
        StringBuilder sb = new StringBuilder();
        while (true) {
            boolean hasMore = false;
            String[] next = new String[cells.length];
            for (int i = 0; i < cells.length; i++) {
                String cell = cells[i].trim();
                int maxCol = Math.min(i, tableColWidth.length - 1);
                int colWidth = tableColWidth[maxCol];
                /* 如果单位是像素，先转成“字符数”再截断 */
                int charWidth = widthIsPixel ?
                        (int) (colWidth / 24f) :   // 24px ≈ 1 个汉字宽
                        colWidth;
                int len = Utils.getStringCharacterLength(cell);
                if (len > charWidth) {
                    int cut = Utils.getSubLength(cell, charWidth);
                    next[i] = cell.substring(cut).trim();
                    cell = cell.substring(0, cut);
                    hasMore = true;
                } else {
                    next[i] = "";
                }
                Align align = columnAlignments[maxCol];
                sb.append(getAlignedText(cell, charWidth, align));
                for (int j = 0; j < colSpacing; j++) sb.append(' ');
            }
            sb.append('\n');
            if (!hasMore) break;
            cells = next;
        }
        return sb.toString();
    }

    private String getAlignedText(String text, int width, Align align) {
        int len = Utils.getStringCharacterLength(text);
        int pad = width - len;
        if (pad <= 0) return text;
        switch (align) {
            case LEFT:
                return text + space(pad);
            case RIGHT:
                return space(pad) + text;
            case CENTER:
                int left = pad / 2;
                return space(left) + text + space(pad - left);
        }
        return text;
    }

    private String space(int n) {
        StringBuilder sb = new StringBuilder(n);
        for (int i = 0; i < n; i++) sb.append(' ');
        return sb.toString();
    }

    /* ---- 供 Table2Bitmap 用的 getter ---- */
    public int getRowSpacing() { return rowSpacing; }
    public int getColSpacing() { return colSpacing; }
    public int[] getTableColWidth() { return tableColWidth; }
    public String getTableReg() { return tableReg; }
    public List<String> getTableRows() { return tableRows; }
    public Align[] getColumnAlignments() { return columnAlignments; }
    public boolean isWidthIsPixel() { return widthIsPixel; }
}