package javalabs.lab4.second;

public class ComplexNumber {
    private double _real;
    private double _imaginary;

    public ComplexNumber(double real, double imaginary) {
        _real = real;
        _imaginary = imaginary;
    }

    public double getReal() { return _real; }
    public void setReal(double real) { _real = real; }

    public double getImaginary() { return _imaginary; }
    public void setImaginary(double imaginary) { _imaginary = imaginary; }

    public ComplexNumber divide(ComplexNumber other) {
        // Z1 = a + bi
        double a = _real;
        double b = _imaginary;

        // Z2 = c + di
        double c = other._real;
        double d = other._imaginary;

        // Знаменатель: c^2 + d^2
        double denominator = c * c + d * d;

        if (denominator == 0) {
            throw new ArithmeticException("Ошибка деления: Делитель не может быть равен нулю (0 + 0i).");
        }

        // Новая Действительная часть: (ac + bd) / (c^2 + d^2)
        double newReal = (a * c + b * d) / denominator;

        // Новая Мнимая часть: (bc - ad) / (c^2 + d^2)
        double newImaginary = (b * c - a * d) / denominator;

        return new ComplexNumber(newReal, newImaginary);
    }

    public void display() {
        System.out.println("Комплексное число: Z = " + this.toString());
        System.out.println("  Действительная часть (Re): " + _real);
        System.out.println("  Мнимая часть (Im): " + _imaginary);
    }

    @Override
    public String toString() {
        if (_imaginary == 0) {
            return String.valueOf(_real);
        }
        if (_real == 0) {
            return _imaginary + "i";
        }
        if (_imaginary < 0) {
            return _real + " - " + (-_imaginary) + "i";
        }
        return _real + " + " + _imaginary + "i";
    }
}