package complex;

import java.util.regex.*;

/**
 * Example Complex number API for CIT 591 class. Minimal
 * comments so the code is more easily visible; see the
 * "add" method for an example of comment style.
 * 
 * @author Dave Matuszek
 * @version Nov 4, 2009
 */
public class Complex {
    private double real;
    private double imaginary;

    public Complex(double real, double imaginary) {
        this.real = real;
        this.imaginary = imaginary;
    }

    public Complex(double real) {
        this.real = real;
        this.imaginary = 0;
    }
    
    public Complex(String complex) {
        int signPosition;
        
        complex = complex.trim();
        if (complex.endsWith("i")) {
            // Trim off the "i"
            complex = complex.substring(0, complex.length() - 1);
            // Locate the (required) sign of the imaginary part
            signPosition = complex.lastIndexOf('+');
            if (signPosition == 0 || signPosition == -1) {
                signPosition = complex.lastIndexOf('-');
            }
            if (signPosition == 0 || signPosition == -1) {
                throw new NumberFormatException();
            }
            // Break into two parts
            real = Double.parseDouble(complex.substring(0, signPosition));
            imaginary = Double.parseDouble(complex.substring(signPosition));
        } else { // No imaginary part
            real = Double.parseDouble(complex);
            imaginary = 0;
        }
    }

    /**
     * Returns the sum of this number and the given number.
     * 
     * @param c The number to be added with this one.
     * @return The sum of the two numbers.
     */
    public Complex add(Complex c) {
        return new Complex(real + c.real, imaginary + c.imaginary);
    }

    public Complex multiply(Complex c) {
        return new Complex(real * c.real - imaginary * c.imaginary,
                           real * c.imaginary + c.real * imaginary);
    }

    @Override
    public boolean equals(Object o) {
        if (!(o instanceof Complex)) {
            return false;
        }
        Complex c = (Complex)o;
        return this.real == c.real &&
               this.imaginary == c.imaginary;
    }

    @Override
    public String toString() {
        if (imaginary == 0) {
            return real + "";
        } else {
            return real + (imaginary > 0 ? "+" : "") +
                   imaginary + "i";
        }
    }
}

