import { Location } from '@angular/common';
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { AllowanceService } from 'src/app/services/allowance.service';

@Component({
    selector: 'app-spend-allowance',
    templateUrl: './add-allowance.page.html',
    styleUrls: ['./add-allowance.page.scss'],
    standalone: false,
})
export class SpendllowancePage {
    public form: FormGroup;
    public goalId: number;
    public userId: number;
    public isAddMode = false;

    constructor(
        private allowanceService: AllowanceService,
        private route: ActivatedRoute,
        private formBuilder: FormBuilder,
        private router: Router,
        private location: Location
    ) {
        this.userId = this.route.snapshot.params['id'];
        this.goalId = this.route.snapshot.params['goalId'];

        this.form = this.formBuilder.group({
        amount: ['', Validators.required],
        description: ['', Validators.required]
        });

        this.allowanceService.getAllowanceById(this.goalId, this.userId).subscribe(allowance => {
            this.form.controls['amount'].addValidators([Validators.max(allowance.progress)]);
        }); 
    }

    changeAllowance() {
        this.allowanceService.addOrSpendAllowance(
        this.goalId,
        this.userId,
        -this.form.value.amount,
        this.form.value.description
        );
        this.router.navigate(['/tabs/allowance', this.userId]);
    }

    navigateBack() {
        this.location.back();
    }
}