package org.kne.codec.kif;

import java.awt.Color;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 颜色统计收集器
 * 用于统计图像中各种颜色出现的频率
 * 继承自 StatisticsCollector<Color>
 */
public class ColorStatisticsCollector extends StatisticsCollector<Color> {
    

	public void analyze(int[] pixels) {
		for (int i : pixels) {
			addRecord(i);
		}
	}
	
    /**
     * 记录一个 RGB 整数值（0x00RRGGBB）的颜色
     */
    public void addRecord(int rgb) {
        Color color = new Color(rgb);
        addRecord(color);
    }
    
    /**
     * 记录一个 RGB 整数值（0x00RRGGBB）的颜色，多次
     */
    public void addRecord(int rgb, long count) {
        Color color = new Color(rgb);
        addRecord(color, count);
    }
    
    /**
     * 记录一个由 R、G、B 分量组成的颜色
     */
    public void addRecord(int r, int g, int b) {
        Color color = new Color(r & 0xFF, g & 0xFF, b & 0xFF);
        addRecord(color);
    }
    
    /**
     * 获取某个 RGB 颜色的出现次数
     */
    public long getCount(int rgb) {
        return getCount(new Color(rgb));
    }
    
    /**
     * 获取某个 RGB 颜色的出现概率（百分比）
     */
    public double getProbability(int rgb) {
        return getProbability(new Color(rgb));
    }
    
    /**
     * 获取最常见的颜色（出现次数最多的颜色）
     */
    public Color getMostFrequentColor() {
        Map<Color, AtomicLong> sorted = getSorted();
        if (sorted.isEmpty()) {
            return null;
        }
        return sorted.entrySet().iterator().next().getKey();
    }
    
    /**
     * 获取最罕见的颜色（出现次数最少的颜色）
     */
    public Color getLeastFrequentColor() {
        Map<Color, AtomicLong> sorted = getSortedAscending();
        if (sorted.isEmpty()) {
            return null;
        }
        return sorted.entrySet().iterator().next().getKey();
    }
    
    /**
     * 获取前 N 种最常见的颜色
     */
    public Map<Color, AtomicLong> getTopColors(int n) {
        Map<Color, AtomicLong> sorted = getSorted();
        return sorted.entrySet().stream()
            .limit(n)
            .collect(java.util.stream.Collectors.toMap(
                Map.Entry::getKey,
                Map.Entry::getValue,
                (old, neu) -> old,
                java.util.LinkedHashMap::new
            ));
    }
    
    /**
     * 获取唯一颜色数量
     */
    public int getColorCount() {
        return getUniqueCount();
    }
    
    /**
     * 生成颜色统计报告
     */
    public String formatColorTable() {
        return formatTable(new ItemFormatter<Color>() {
            @Override
            public String format(Color color) {
                return String.format("RGB(%d,%d,%d)",
                    color.getRed(),
                    color.getGreen(),
                    color.getBlue()
                );
            }
        });
    }
    /**
     * 生成颜色统计报告（带颜色名称/简写）
     */
    public String formatColorTable(boolean showName) {
        if (!showName) {
            return formatColorTable();
        }
        
        long t = total.get();
        if (t == 0) {
            return "（无统计数据）";
        }
        
        StringBuilder sb = new StringBuilder();
        sb.append("╔═══════════════════════════════════════════════════════════════════════════════════╗\n");
        sb.append("║                        颜色统计报告                                            ║\n");
        sb.append("╠═══════════════════════════════════════════════════════════════════════════════════╣\n");
        sb.append("║  序号  │  颜色                         │  出现次数  │  占比      │  累积占比     ║\n");
        sb.append("╠═══════════════════════════════════════════════════════════════════════════════════╣\n");
        
        Map<Color, AtomicLong> sorted = getSorted();
        long cumulative = 0;
        int index = 0;
        
        for (Map.Entry<Color, AtomicLong> entry : sorted.entrySet()) {
            Color color = entry.getKey();
            long count = entry.getValue().get();
            double pct = count * 100.0 / t;
            cumulative += count;
            double cumPct = cumulative * 100.0 / t;
            index++;
            
            String colorStr = String.format("RGB(%d,%d,%d)",
                color.getRed(),
                color.getGreen(),
                color.getBlue()
            );
            if (colorStr.length() > 27) {
                colorStr = colorStr.substring(0, 24) + "...";
            }
            
            sb.append(String.format("║  %4d  │  %-27s  │  %8d  │  %6.2f%%  │  %6.2f%%  ║\n",
                index,
                colorStr,
                count,
                pct,
                cumPct
            ));
        }
        
        sb.append("╠═══════════════════════════════════════════════════════════════════════════════════╣\n");
        sb.append(String.format("║  总像素数: %d  │  唯一颜色数: %d  │  覆盖率: %6.2f%%                     ║\n",
            t,
            getUniqueCount(),
            100.0
        ));
        sb.append("╚═══════════════════════════════════════════════════════════════════════════════════╝");
        return sb.toString();
    }
    
    /**
     * 生成简洁的颜色统计摘要
     */
    public String getSummary() {
        long t = total.get();
        if (t == 0) {
            return "无数据";
        }
        
        Color mostFrequent = getMostFrequentColor();
        Color leastFrequent = getLeastFrequentColor();
        
        return String.format(
            "总像素数: %d, 唯一颜色数: %d, 最频繁颜色: RGB(%d,%d,%d) (%.2f%%), 最罕见颜色: RGB(%d,%d,%d) (%.2f%%)",
            t,
            getUniqueCount(),
            mostFrequent.getRed(), mostFrequent.getGreen(), mostFrequent.getBlue(),
            getProbability(mostFrequent),
            leastFrequent.getRed(), leastFrequent.getGreen(), leastFrequent.getBlue(),
            getProbability(leastFrequent)
        );
    }

}