import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-calculator',
  templateUrl: './calculator.component.html',
  styleUrls: ['./calculator.component.scss']
})
export class CalculatorComponent implements OnInit {
  display: string = '0';
  currentNumber: string = '';
  firstOperand: number | null = null;
  operator: string | null = null;
  waitForSecondOperand: boolean = false;

  constructor() { }

  ngOnInit(): void {
  }

  appendNumber(num: string) {
    if (this.display === 'Error') {
      this.resetState();
    }
    if (this.waitForSecondOperand) {
      this.display = num;
      this.currentNumber = num;
      this.waitForSecondOperand = false;
    } else {
      this.currentNumber = this.currentNumber === '0' ? num : this.currentNumber + num;
      this.display = this.currentNumber;
    }
  }

  appendOperator(op: string) {
    if (this.display === 'Error') {
      this.resetState();
    }
    if (this.firstOperand === null) {
      this.firstOperand = parseFloat(this.currentNumber);
    } else if (this.operator) {
      const result = this.performCalculation(this.operator, this.firstOperand, parseFloat(this.currentNumber));
      if (isNaN(result)) {
        this.display = 'Error';
        this.resetState();
        return;
      }
      this.display = String(result);
      this.firstOperand = result;
    }
    this.operator = op;
    this.waitForSecondOperand = true;
  }

  calculate() {
    if (this.firstOperand !== null && this.operator !== null && this.currentNumber !== '') {
      const result = this.performCalculation(this.operator, this.firstOperand, parseFloat(this.currentNumber));
      if (isNaN(result)) {
        this.display = 'Error';
        this.resetState();
        return;
      }
      this.display = String(result);
      this.firstOperand = result;
      this.currentNumber = String(result);
      this.operator = null;
      this.waitForSecondOperand = false;
    }
  }

  private performCalculation(operator: string, operand1: number, operand2: number): number {
    switch (operator) {
      case '+':
        return operand1 + operand2;
      case '-':
        return operand1 - operand2;
      case '*':
        return operand1 * operand2;
      case '/':
        if (operand2 === 0) {
          // Handle division by zero
          return NaN; // Or throw an error, or display "Error"
        }
        return operand1 / operand2;
      default:
        return operand2;
    }
  }
}
