// 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 { SettingsMotionEditComponent } from './edit.motion.component';
import { MotionService } from '../../../services/motion.service';
import { MotionModel } from '../../../model/motion.model';
import { MotionCategoryModel } from '../../../model/motion.category.model';

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

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

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

	private load(categoryId?: string) {
		this.motionService.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: MotionCategoryModel) {
		this.selectedCategory = category;
		this.motionService.getMotions(category.id)
			.subscribe(data => {
				this.motions = data;
			});
	}

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

	public remove(category: MotionModel) {
		Swal.fire({
			title: 'Remove motion ' + 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();
		});
	}
}
