// angular
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';

// libs
import { MatDialog } from '@angular/material/dialog';

// app
import { ApiRoutes } from '../../../api-routes';
import { SettingsConnectCurrencyComponent } from './connect.currency.component';
import { CurrencyModel } from '../../../model/currency.model';
import { SettingsRateCurrencyComponent } from './rate.currency.component';

@Component({
	templateUrl: './currency.component.html',
	styleUrls: ['./currency.component.scss'],
})
export class SettingsCurrencyComponent {
	public tabIndex = 0;

	public currencies?: CurrencyModel[];
	public myCurrencies?: CurrencyModel[];
	public primaryId?: string;

	constructor(
		private httpClient: HttpClient,
		private dialogModel: MatDialog
	) {
	}

	ngOnInit(): void {
		this.load();
	}

	connect(currency: CurrencyModel) {
		this.dialogModel.open(SettingsConnectCurrencyComponent, {
			width: '640px',
			disableClose: true,
			data: currency,
		}).afterClosed().subscribe(x => {
			if (x && x.refresh) {
				this.tabIndex = 0;
				this.loadMyCurrency();
			}
		});
	}

	disconnect(currency: CurrencyModel) {
	}

	setRate(currency: CurrencyModel) {
		this.dialogModel.open(SettingsRateCurrencyComponent, {
			width: '640px',
			disableClose: true,
			data: currency,
		}).afterClosed().subscribe(x => {
			if (x && x.refresh) {
				this.loadMyCurrency();
			}
		});
	}

	private load() {
		this.httpClient
			.get<CurrencyModel[]>(ApiRoutes.GeneralCurrencies)
			.subscribe(data => {
				this.currencies = data;
				this.loadMyCurrency();
			});
	}

	private loadMyCurrency() {
		this.httpClient
			.get<CurrencyModel[]>(ApiRoutes.SettingsCurrencies)
			.subscribe(data => {
				this.myCurrencies = data.map(myCurrency => {
					var globalCurrency = this.currencies?.find(x => x.id === myCurrency.code);

					return {
						id: myCurrency.id,
						code: myCurrency.code,
						name: myCurrency.name,
						quantity: myCurrency.quantity,
						rate: myCurrency.rate,
						rateDate: myCurrency.rateDate,
						shortName: myCurrency.shortName,
						symbol: globalCurrency?.symbol,
						isPrimary: myCurrency.isPrimary,
					};
				});
			});
	}
}
