package com.metaweb.lessen.tokens;

abstract public class Color extends Token {
    protected Color(int start, int end, String text) {
        super(Type.Color, start, end, text);
    }

    abstract public int getR();
    abstract public int getG();
    abstract public int getB();
    abstract public int getA();
    
    public Color performOperation(String op, Color color) {
        int mult = op.equals("+") ? 1 : -1;
        
        StringBuffer sb = new StringBuffer();
        sb.append('#');
        
        int r = limitComponent(getR() + mult * color.getR()); sb.append(numberToHex(r));
        int g = limitComponent(getG() + mult * color.getG()); sb.append(numberToHex(g));
        int b = limitComponent(getB() + mult * color.getB()); sb.append(numberToHex(b));
        int a = -1;
        if (getA() >= 0) {
            if (color.getA() >= 0) {
                a = limitComponent(getA() + mult * color.getA());
            } else {
                a = getA();
            }
            sb.append(numberToHex(a));
            
        } else if (color.getA() >= 0 && mult > 0) {
            a = color.getA(); sb.append(numberToHex(a));
        }
        
        return new OneTokenColor(
            start, end, sb.toString(),
            r, g, b, a
        );
    }
    
    public Color performOperation(String op, Number n) {
        double mult = op.equals("*") ? n.doubleValue() : (1 / n.doubleValue());
        
        StringBuffer sb = new StringBuffer();
        sb.append('#');
        
        int r = limitComponent((int) (getR() * mult)); sb.append(numberToHex(r));
        int g = limitComponent((int) (getG() * mult)); sb.append(numberToHex(g));
        int b = limitComponent((int) (getB() * mult)); sb.append(numberToHex(b));
        int a = -1;
        if (getA() >= 0) {
            a = limitComponent((int) (getA() * mult));
            
            sb.append(numberToHex(a));
        }
        
        return new OneTokenColor(
            start, end, sb.toString(),
            r, g, b, a
        );
    }
    
    protected String numberToHex(int n) {
        String s = Integer.toHexString(n);
        return s.length() > 1 ? s : "0" + s;
    }
    
    protected int limitComponent(int n) {
        return Math.max(0, Math.min(255, n));
    }
}
