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

// libs
import Swal from 'sweetalert2';

// app
import { ApiRoutes } from '../../../api-routes';
import { MotionCategoryModel } from '../../../model/motion.category.model';

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

	constructor(
		private httpClient: HttpClient,
	) {
	}

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

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

	public add() {
		Swal.fire({
			title: 'Motion category name',
			input: 'text',
			inputAttributes: {
				autocapitalize: 'off',
			},
			showCancelButton: true,
			confirmButtonText: 'Add',
			showLoaderOnConfirm: true,
			preConfirm: (name) => {
				return new Promise((resolve, reject) => {
					this.httpClient.post(ApiRoutes.SettingsMotionCategories, { 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: MotionCategoryModel) {
		Swal.fire({
			title: 'Motion 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.SettingsMotionCategory.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: MotionCategoryModel) {
		Swal.fire({
			title: 'Remove motion category ' + category.name,
			showCancelButton: true,
			confirmButtonText: 'Delete',
			showLoaderOnConfirm: true,
			preConfirm: (name) => {
				return new Promise((resolve, reject) => {
					this.httpClient.delete(ApiRoutes.SettingsMotionCategory.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();
		});
	}
}
