import { ChangeDetectionStrategy, ChangeDetectorRef, Component, Input, OnChanges, OnInit, SimpleChanges } from '@angular/core';

@Component({
  selector: 'ui-circle-progress',
  templateUrl: 'ui-circle-progress.component.html',
  styleUrls: ['ui-circle-progress.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class UiCircleProgressComponent implements OnChanges {
  @Input()
  size: number = 100;

  @Input()
  strokeWidth: number = 12;

  @Input()
  background: string = '#e6eff9';

  @Input()
  foreground: string = '#26830c';

  @Input()
  progress: number = 0;

  radius: number;
  circumference: number;
  dashoffset: number;

  constructor(private cdr: ChangeDetectorRef) {
    this.calculateProgress(this.progress);
  }

  ngOnChanges({ progress, size, strokeWidth }: SimpleChanges): void {
    if (progress || size || strokeWidth) {
      this.calculateProgress(this.progress);
    }
  }

  calculateProgress(value: number): void {
    value = Math.min(Math.max(0, value), 100);
    this.radius = this.size / 2 - this.strokeWidth / 2;
    this.circumference = 2 * Math.PI * this.radius;
    this.dashoffset = this.circumference * (1 - value / 100);

    this.cdr.markForCheck();
  }
}
