// angular
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Inject } from '@angular/core';
import { UntypedFormBuilder } from '@angular/forms';
import { UntypedFormGroup } from '@angular/forms';
import { Validators } from '@angular/forms';

// libs
import Swal from 'sweetalert2';
import { MAT_DIALOG_DATA } from '@angular/material/dialog';

// app
import { ApiRoutes } from '../../../api-routes';
import { MatDialogRef } from '@angular/material/dialog';
import { AccountCategoryModel } from '../../../model/account.category.model';
import { MotionModel } from '../../../model/motion.model';
import { MotionService } from '../../../services/motion.service';

@Component({
	templateUrl: './edit.motion.component.html',
	styleUrls: ['./edit.motion.component.scss'],
})
export class SettingsMotionEditComponent {
	public editForm!: UntypedFormGroup;
	public errorMessage?: string;
	public categories?: AccountCategoryModel[];

	constructor(
		private fb: UntypedFormBuilder,
		private httpClient: HttpClient,
		private dialogRef: MatDialogRef<SettingsMotionEditComponent>,
		private motionService: MotionService,
		@Inject(MAT_DIALOG_DATA) public motion: MotionModel
	) {
	}

	ngOnInit(): void {
		this.editForm = this.fb.group({
			id: [
				this.motion.id,
			],
			name: [
				this.motion.name,
				[Validators.required],
			],
			category: [
				this.motion.categoryId,
				[Validators.required],
			],
		});

		this.motionService
			.getCategories()
			.subscribe(x => this.categories = x);
	}

	closeDialog(): void {
		this.dialogRef.close();
	}

	onSubmitClick() {
		if (this.editForm.valid) {
			this.errorMessage = undefined;
			this.httpClient
				.put<MotionModel>(ApiRoutes.SettingsMotion.replace(':id', this.motion.id!), this.editForm.value)
				.subscribe(response => {
					this.dialogRef.close({ motion: response, refresh: true });
				}, error => {
					this.errorMessage = error.detail;
				});
		}
	}
}
