// 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 { SettingsItemEditComponent } from './edit.item.component';
import { ItemService } from '../../../services/item.service';
import { ItemModel } from '../../../model/item.model';
import { ItemCategoryModel } from '../../../model/item.category.model';

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

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

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

	private load(categoryId?: string) {
		this.itemService.getCategories()
			.subscribe(data => {
				this.categories = data;
				var selected = data[0];
				if (categoryId) {
					var categories = this.categories.filter(x => x.id === categoryId);
					selected = categories.length === 0
						? selected
						: categories[0];
				}

				this.selectCategory(selected);
			});
	}

	public selectCategory(category: ItemCategoryModel) {
		this.selectedCategory = category;
		this.itemService.getItems(category.id)
			.subscribe(data => {
				this.items = data;
			});
	}

	public edit(item: ItemModel) {
		this.dialogModel.open(SettingsItemEditComponent, {
			width: '640px',
			disableClose: true,
			data: item,
		}).afterClosed().subscribe(x => {
			if (x && x.refresh) {
				console.log(x.motion.categoryId);
				this.load(x.motion.categoryId);
			}
		});
	}

	public remove(category: ItemModel) {
		Swal.fire({
			title: 'Delete item from ' + 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();
		});
	}
}
