/*
 * @(#)ColorBorder.java  1.0  2008-10-04
 * 
 * Copyright (c) 2008 Werner Randelshofer, Immensee, Switzerland.
 * All rights reserved.
 *
 * You may not use, copy or modify this file, except in compliance with the
 * license agreement you entered into with Werner Randelshofer.
 * For details see accompanying license terms.
 */
package ch.randelshofer.gui.border;

import java.awt.*;
import javax.swing.border.Border;

/**
 * ColorBorder.
 *
 * @author Werner Randelshofer, Hausmatt 10, CH-6405 Immensee
 * @version 1.0 2008-10-04 Created.
 */
public class ColorBorder implements Border {

    private Insets insets;
    private Color color;

    public ColorBorder(Color color, Insets insets) {
        this.color = color;
        this.insets = insets;
    }

    public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
        if (width <= 0 || height <= 0) {
            return;
        }

        g.setColor(color);

        if (insets.top + insets.bottom >= height) {
            // Fill everything
            g.fillRect(x + insets.left, y, width - insets.left - insets.right, height);
        } else {
            // Fill top and bottom inclusive corners
            if (insets.top > 0) {
                int h = Math.min(insets.top, height);
                g.fillRect(x, y, width, h);
            }
            if (insets.bottom > 0) {
                int h = Math.min(insets.bottom, height);
                g.fillRect(x, y + height - h, width, h);
            }

            if (insets.left + insets.right >= width) {
                g.fillRect(x, y+insets.top, width, height-insets.top-insets.bottom);
            } else {
            // Fill left and right exclusive corners
                if (insets.left > 0) {
                    g.fillRect(x, y+insets.top, insets.left, height-insets.top-insets.bottom);
                }
                if (insets.right > 0) {
                    g.fillRect(x + width - insets.right, y + insets.top, insets.right, height-insets.top-insets.bottom);
                }
            }
        }
    }

    public Insets getBorderInsets(Component c) {
        return (Insets) insets.clone();
    }

    public boolean isBorderOpaque() {
        return color.getTransparency() == Paint.OPAQUE;
    }

    public static class UIResource extends ColorBorder implements javax.swing.plaf.UIResource {

        public UIResource(Color color, Insets insets) {
            super(color, insets);
        }
    }
}
