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

// libs
import Swal from 'sweetalert2';

// app
import { ApiRoutes } from '../../../api-routes';
import { AccountCategoryModel } from '../../../model/account.category.model';

@Component({
	templateUrl: './account.category.component.html',
	styleUrls: ['./account.category.component.scss'],
})
export class SettingsAccountCategoryComponent {
	public categories?: AccountCategoryModel[];

	constructor(
		private httpClient: HttpClient,
	) {
	}

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

	private load() {
		this.httpClient
			.get<AccountCategoryModel[]>(ApiRoutes.SettingsAccountCategories)
			.subscribe(data => {
				this.categories = data;
			});
	}

	public add() {
		Swal.fire({
			title: 'Account category name',
			input: 'text',
			inputAttributes: {
				autocapitalize: 'off',
			},
			showCancelButton: true,
			confirmButtonText: 'Add',
			showLoaderOnConfirm: true,
			preConfirm: (name) => {
				return new Promise((resolve, reject) => {
					this.httpClient.post(ApiRoutes.SettingsAccountCategories, { name: name })
						.subscribe(data => {
							resolve(data);
						}, error => {
							Swal.showValidationMessage(error.detail);
							reject();
						});

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

	public edit(category: AccountCategoryModel) {
		Swal.fire({
			title: 'Account category name',
			input: 'text',
			inputValue: category.name,
			inputAttributes: {
				autocapitalize: 'off',
			},
			showCancelButton: true,
			confirmButtonText: 'Update',
			showLoaderOnConfirm: true,
			preConfirm: (name) => {
				return new Promise((resolve, reject) => {
					this.httpClient.put(ApiRoutes.SettingsAccountCategory.replace(':id', category.id!), { name: name })
						.subscribe(data => {
							resolve(data);
						}, error => {
							Swal.showValidationMessage(error.detail);
							reject();
						});

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

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

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