// 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 { MAT_DIALOG_DATA } from '@angular/material/dialog';
import { MatDialogRef } from '@angular/material/dialog';

// app
import { ApiRoutes } from '../../../api-routes';
import { ItemCategoryModel } from '../../../model/item.category.model';

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

	constructor(
		private fb: UntypedFormBuilder,
		private httpClient: HttpClient,
		private dialogRef: MatDialogRef<SettingsItemCategoryEditComponent>,
		@Inject(MAT_DIALOG_DATA) public category: ItemCategoryModel
	) {
	}

	ngOnInit(): void {
		this.editForm = this.fb.group({
			id: [
				this.category.id,
			],
			name: [
				this.category.name,
				[Validators.required],
			],
			isInternal: [
				this.category.isInternal,
			],
		});
		console.log(this.editForm.value);
	}

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

	onSubmitClick() {
		if (this.editForm.valid) {
			this.errorMessage = undefined;
			if (!this.category.id) {
				this.httpClient
					.post<ItemCategoryModel>(ApiRoutes.SettingsItemCategories, this.editForm.value)
					.subscribe(response => {
						this.dialogRef.close({ category: response, refresh: true });
					}, error => {
						this.errorMessage = error.detail;
					});
			} else {
				this.httpClient
					.put<ItemCategoryModel>(ApiRoutes.SettingsItemCategory.replace(':id', this.category.id!), this.editForm.value)
					.subscribe(response => {
						this.dialogRef.close({ category: response, refresh: true });
					}, error => {
						this.errorMessage = error.detail;
					});
			}
		}
	}
}
