// angular
import { Component, DestroyRef, inject } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { HttpClient } from '@angular/common/http';

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

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

	private readonly destroyRef = inject(DestroyRef);

	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()
			.pipe(takeUntilDestroyed(this.destroyRef))
			.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()
			.pipe(takeUntilDestroyed(this.destroyRef))
			.subscribe(x => {
			if (x && x.refresh) {
				this.loadMyCurrency();
			}
		});
	}

	delete(currency: CurrencyModel) {
		Swal.fire({
			title: 'Delete currency ' + currency.name,
			showCancelButton: true,
			confirmButtonText: 'Delete',
			showLoaderOnConfirm: true,
			preConfirm: (name) => {
				return new Promise((resolve, reject) => {
					this.httpClient.delete(ApiRoutes.SettingsCurrency.replace(':id', currency.id!))
						.pipe(takeUntilDestroyed(this.destroyRef))
						.subscribe(data => {
							resolve(data);
						}, error => {
							Swal.showValidationMessage(error.detail);
							reject();
						});

				}).catch(x => {
					return false;
				});
			},
			allowOutsideClick: () => !Swal.isLoading(),
		}).then((result) => {
			this.load();
		});

	}

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

	private loadMyCurrency() {
		this.httpClient
			.get<CurrencyModel[]>(ApiRoutes.SettingsCurrencies)
			.pipe(takeUntilDestroyed(this.destroyRef))
			.subscribe(data => {
				this.myCurrencies = data
					.sort((a, b) => a.code!.localeCompare(b.code!))
					.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,
						};
					});
			});
	}
}
