/*
 * Copyright 2008 Estalea, Inc. All rights reserved.
 * This software is the proprietary information of Estalea, Inc.
 */

package org.forkalsrud.album.exif;


/**
 *
 * @author knut
 */
public class Dimension {

    int w;
    int h;

    public Dimension(Dimension other) {
    	this.w = other.w;
    	this.h = other.h;
    }

    public Dimension(int w, int h) {
        this.w = w;
        this.h = h;
    }

    public Dimension(String s) {
        String[] coords;
        if (s.contains("x")) {
            coords = s.split("x");
        } else if (s.contains(" ")) {
            coords = s.split(" ");
        } else {
            throw new RuntimeException("Bad dimension: " + s);
        }
        this.w = Integer.parseInt(coords[0]);
        this.h = Integer.parseInt(coords[1]);
    }


    public Dimension(String width, String height) {
        this(Integer.parseInt(width), Integer.parseInt(height));
    }

    public Dimension doubled() {

    	return new Dimension(w * 2, h * 2);
    }

    public Dimension halved() {

    	return new Dimension(w / 2, h / 2);
    }

    public Dimension scaled(int max) {

        return w > h ? scaleWidth(max) : scaleHeight(max);
    }


    public Dimension scaleWidth(int maxWidth) {
        return new Dimension(maxWidth, (maxWidth * h + maxWidth / 2) / w);
    }

    public Dimension scaleHeight(int maxHeight) {
        return new Dimension((maxHeight * w + maxHeight / 2) / h, maxHeight);
    }


    public Dimension flip() {
        return new Dimension(h, w);
    }


    @Override
    public String toString() {
        return w + "x" + h;
    }


    public int getWidth() {
        return w;
    }

    public int getHeight() {
        return h;
    }

    /**
     * @param size
     * @return
     */
    public Dimension scale(String size) {
        Dimension outd;
    	if (size.endsWith("h")) {
    		int height = Integer.parseInt(size.substring(0, size.length() - 1));
    		outd = scaleHeight(height);
    	} else if (size.endsWith("w")) {
    		int width = Integer.parseInt(size.substring(0, size.length() - 1));
    		outd = scaleWidth(width);
    	} else {
    		int worh = Integer.parseInt(size);
    		outd = scaled(worh);
    	}
        return outd;
    }



    public Dimension even() {
    	return new Dimension(this.w % 2 > 0 ? this.w + 1 : this.w,
    						 this.h % 2 > 0 ? this.h + 1 : this.h);
    }

}
