// angular
import { Component } from '@angular/core';
import { Inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { UntypedFormBuilder } from '@angular/forms';
import { UntypedFormGroup } from '@angular/forms';
import { Validators } from '@angular/forms';

// libs
import { MatDialogRef } from '@angular/material/dialog';
import { MAT_DIALOG_DATA } from '@angular/material/dialog';
import { CurrencyMaskInputMode, NgxCurrencyModule } from "ngx-currency";

// app
import { ApiRoutes } from '../../../api-routes';
import { CurrencyModel } from '../../../model/currency.model';

@Component({
	templateUrl: './rate.currency.component.html',
	styleUrls: ['./rate.currency.component.scss'],
})
export class SettingsRateCurrencyComponent {
	public addForm!: UntypedFormGroup;
	public errorMessage?: string;

	constructor(
		private fb: UntypedFormBuilder,
		private httpClient: HttpClient,
		private dialogRef: MatDialogRef<SettingsRateCurrencyComponent>,
		@Inject(MAT_DIALOG_DATA) public currency: CurrencyModel
	) {
	}

	public ngOnInit(): void {
		this.addForm = this.fb.group({
			id: [
				this.currency.id,
			],
			code: [
				this.currency.code,
			],
			symbol: [
				this.currency.symbol,
			],
			name: [
				this.currency.name,
			],
			shortName: [
				this.currency.shortName,
			],
			quantity: [
				this.currency.quantity || 1,
				[Validators.required],
			],
			rate: [
				this.currency.rate || 1,
				[Validators.required],
			],
			rateDate: [
				this.currency.rateDate,
				[Validators.required],
			],
			isPrimary: [
				this.currency.isPrimary,
			],
		});
	}

	closeDialog(): void {
		this.dialogRef.close();
	}

	onSubmitClick() {
		if (this.addForm.valid) {
			this.errorMessage = undefined;
			this.httpClient
				.put<CurrencyModel>(ApiRoutes.SettingsCurrency.replace(':id', this.addForm.value.id), this.addForm.value)
				.subscribe(response => {
					this.httpClient
						.post<CurrencyModel[]>(ApiRoutes.SettingsCurrenciesRate.replace(':id', this.addForm.value.id), this.addForm.value)
						.subscribe(response => {
							this.dialogRef.close({ refresh: true });
						}, error => {
							this.errorMessage = error.detail;
						});
				}, error => {
					this.errorMessage = error.detail;
				});
		}
	}
}
