import { Component } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { BehaviorSubject } from 'rxjs';
import { Allowance } from 'src/app/models/allowance';
import { AllowanceService } from 'src/app/services/allowance.service';
import hexRgb from 'hex-rgb';
import { ViewWillEnter } from '@ionic/angular';

@Component({
  selector: 'app-allowance',
  templateUrl: 'allowance.page.html',
  styleUrls: ['allowance.page.scss'],
  standalone: false,
})
export class AllowancePage implements ViewWillEnter {
  private id: number;
  public allowance$: BehaviorSubject<Array<Allowance>> = new BehaviorSubject<Array<Allowance>>([]);

  constructor(
    private route: ActivatedRoute,
    private router: Router,
    private allowanceService: AllowanceService
  ) {
    this.id = this.route.snapshot.params['id'];
    this.getAllowance();
  }

  ionViewWillEnter(): void {
    this.getAllowance();
  }

  getAllowance() {
    setTimeout(() => {
      this.allowanceService.getAllowanceList(this.id).subscribe(allowance => {
        allowance[0].colour = '#9C4BE4';
        allowance[0].name = 'Main Allowance';
        this.allowance$.next(allowance);
      })
    }, 100);
  }

  canFinishGoal(allowance: Allowance): boolean {
    return allowance.progress >= allowance.target;
  }

  hexToRgb(color: string) {
    return hexRgb(color, { alpha: 0.3, format: 'css' })
  }

  getPercentage(allowance: Allowance): number {
    return allowance.progress / allowance.target * 100;
  }

  // Returns number in percent
  getPartitionSize(goal: Allowance, allowanceList: Array<Allowance>): number {
    let allowanceTotal = 0;
    for (let allowance of allowanceList) {
      allowanceTotal += allowance.progress;
    }
    if (allowanceTotal === 0) {
      return 0;
    }
    return goal.progress / allowanceTotal * 100;
  }

  createAllowance() {
    this.router.navigate(['add'], { relativeTo: this.route });
  }

  updateAllowance(id: number) {
    this.router.navigate(['edit', id], { relativeTo: this.route });
  }

  completeGoal(goalId: number) {
    this.allowanceService.completeGoal(goalId, this.id);
    this.getAllowance();
  }

  addAllowance(id: number) {
    this.router.navigate(['increase', id], { relativeTo: this.route });
  }

  spendAllowance(id: number) {
    this.router.navigate(['spend', id], { relativeTo: this.route });
  }
}
