// angular
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { ActivatedRoute } from '@angular/router';
import { UntypedFormBuilder } from '@angular/forms';
import { Validators } from '@angular/forms';
import { UntypedFormGroup } from '@angular/forms';
import { Input } from '@angular/core';
import { Output } from '@angular/core';
import { EventEmitter } from '@angular/core';

// libs
import Swal from 'sweetalert2';
import { MatDialog } from '@angular/material/dialog';
import * as moment from 'moment';

// app
import { AccountCategoryService } from '../../services/account.category.service';
import { ApiRoutes } from '../../api-routes';
import { AccountCategoryModel } from '../../model/account.category.model';
import { SettingsAccountAddComponent } from '../settings/account/add.account.component';
import { SettingsAccountEditComponent } from '../settings/account/edit.account.component';
import { AccountModel } from '../../model/account.model';
import { AccountDetailedModel } from '../../model/account.detailed.model';
import { AccountMotionModel } from '../../model/account.motion';
import { atLeastOne } from '../../core/validators/atleastone.validator';
import { atLeastOneNumber } from '../../core/validators/atleastonenumber.validator';

@Component({
	selector: 'account-motion',
	templateUrl: './motion.component.html',
	styleUrls: ['./motion.component.scss'],
})
export class MotionComponent {
	public form!: UntypedFormGroup;
	public errorMessage?: string;

	@Input() motion!: AccountMotionModel;

	constructor(
		private fb: UntypedFormBuilder,
		private httpClient: HttpClient,
		private dialogModel: MatDialog,
		private activatedRoute: ActivatedRoute
	) {
	}

	ngOnInit(): void {
		this.form = this.fb.group({
			id: [
				this.motion.id,
			],
			date: [
				this.motion.date,
				[Validators.required],
			],
			motion: [
				this.motion.motion,
				[Validators.required],
			],
			description: [
				this.motion.description,
			],
			plus: [
				this.motion.plus,
			],
			minus: [
				this.motion.minus,
			],
		}, { validator: atLeastOneNumber(Validators.required, ['plus', 'minus']) });
	}

	onSubmitClick() {
		if (this.form.valid) {
			this.httpClient
				.post<AccountMotionModel[]>(ApiRoutes.SettingsCurrencies, this.form.value)
				.subscribe(response => {
				}, error => {
					this.errorMessage = error.detail;
				});
		}
	}

	addDay(days: number) {
		var date = moment(this.form!.get('date')!.value).add(days, 'days').toDate();
		this.form.patchValue({
			date: date,
		});
	}
}
