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

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

// app
import { ApiRoutes } from '../../../api-routes';
import { AccountModel } from '../../../model/account.model';
import { AccountCategoryModel } from '../../../model/account.category.model';
import { SettingsAccountAddComponent } from './add.account.component';
import { SettingsAccountEditComponent } from './edit.account.component';
import { AccountCategoryService } from '../../../services/account.category.service';

@Component({
	templateUrl: './account.component.html',
	styleUrls: ['./account.component.scss'],
})
export class SettingsAccountComponent {
	public accountCategories?: AccountCategoryModel[];
	public accounts?: AccountModel[];

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

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

	private loadAccounts() {
		this.httpClient
			.get<AccountModel[]>(ApiRoutes.SettingsAccounts)
			.subscribe(data => {
				this.accounts = data;
			});
	}

	private loadCategories() {
		this.accountCategoryService
			.getCategories()
			.subscribe(x => {
				this.accountCategories = x;
				this.loadAccounts();
			});
	}

	public accountInCategory(category?: AccountCategoryModel) {
		if (this.accounts) {
			return this.accounts.filter(acc => (!category && (!acc.categories || acc.categories.length === 0)) || (category && acc.categories && acc.categories.filter(cat => cat.id === category.id).length > 0));
		}
		return null;
	}

	public add() {
		this.dialogModel.open(SettingsAccountAddComponent, {
			width: '640px',
			disableClose: true,
			data: this.accounts,
		}).afterClosed().subscribe(x => {
			if (x && x.refresh) {
				this.loadAccounts();
			}
		});
	}

	public edit(account: AccountModel) {
		this.dialogModel.open(SettingsAccountEditComponent, {
			width: '640px',
			disableClose: true,
			data: account,
		}).afterClosed().subscribe(x => {
			if (x && x.refresh) {
				this.loadAccounts();
			}
		});
	}

	public remove(account: AccountModel) {
		Swal.fire({
			title: 'Remove account ' + account.name,
			showCancelButton: true,
			confirmButtonText: 'Delete',
			showLoaderOnConfirm: true,
			preConfirm: (name) => {
				return new Promise((resolve, reject) => {
					this.httpClient.delete(ApiRoutes.SettingsAccount.replace(':id', account.id!))
						.subscribe(data => {
							resolve(data);
						}, error => {
							Swal.showValidationMessage(error.detail);
							reject();
						});

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