// 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';

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

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

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

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

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

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