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

@Component({
  selector: 'app-ng-roman-number',
  templateUrl: './ng-roman-number.component.html',
  styleUrls: ['./ng-roman-number.component.css']
})
export class NgRomanNumberComponent implements OnInit {
  @Input() ngNumber;
  result = "";
  constructor() { }

  ngOnInit() {
    const incommingNumber = this.ngNumber;
    this.ngNumber = this.getNumber(incommingNumber);
  }
  getNumber(natural) {
    this.result ="";
    if (natural === NaN) {
      return null;
    } while (natural !== 0) {

      if (natural >= 1000) {
        this.postdigit('M', natural / 1000);
        natural = natural - Math.trunc(natural / 1000) * 1000;
      } else if (natural >= 500) {
        if (natural < 900) {
          this.postdigit('D', natural / 500);
          natural = natural - Math.trunc(natural / 500) * 500;
        } else {
          this.predigit('C', 'M');
          natural = natural - (1000 - 100);
        }
      } else if (natural >= 100) {
        if (natural < 400) {
          this.postdigit('C', natural / 100);
          natural = natural - Math.trunc(natural / 100) * 100;
        } else {
          this.predigit('C', 'D');
          natural = natural - (500 - 100);
        }
      } else if (natural >= 50) {


        if (natural < 90) {
          this.postdigit('L', natural / 50);
          natural = natural - Math.trunc(natural / 50) * 50;
        } else {
          this.predigit('X', 'C');
          natural = natural - (100 - 10);
        }

      } else if (natural >= 10) {


        if (natural < 40) {
          this.postdigit('X', natural / 10);
          natural = natural - Math.trunc(natural / 10) * 10;
        } else {
          this.predigit('X', 'L');
          natural = natural - (50 - 10);
        }
      } else if (natural >= 5) {
        if (natural < 9) {
          this.postdigit('V', natural / 5);
          natural = natural - Math.trunc(natural / 5) * 5;
        } else {
          this.predigit('I', 'X');
          natural = natural - (10 - 1);
        }
      } else if (natural >= 1) {
        if (natural < 4) {
          this.postdigit('I', natural / 1);
          natural = natural - Math.trunc(natural / 1) * 1;
        } else {
          this.predigit('I', 'V');
          natural = natural - (5 - 1);
        }
      }
    }
    return this.result;
  }
  predigit(num1, num2) {
    this.result = this.result + num1;
    this.result = this.result + num2;


  }

  postdigit(c, n) {
    n = Math.trunc(n);
    for (let j = 0; j < n; j++) {

      this.result = this.result + c;
    }
  }
}
