// 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 { ItemCategoryModel } from '../../../model/item.category.model';
import { SettingsItemCategoryEditComponent } from './edit.item.category.component';

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

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

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

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

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

	public edit(category: ItemCategoryModel) {
		this.dialogModel.open(SettingsItemCategoryEditComponent, {
			width: '640px',
			disableClose: true,
			data: category,
		}).afterClosed().subscribe(x => {
			if (x && x.refresh) {
				this.load();
			}
		});
	}

	public remove(category: ItemCategoryModel) {
		Swal.fire({
			title: 'Delete item category ' + category.name,
			showCancelButton: true,
			confirmButtonText: 'Delete',
			showLoaderOnConfirm: true,
			preConfirm: (name) => {
				return new Promise((resolve, reject) => {
					this.httpClient.delete(ApiRoutes.SettingsItemCategory.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();
		});
	}
}
