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

// libs
import * as moment from 'moment';
import { Observable } from 'rxjs';

// app
import { ApiRoutes } from '../../api-routes';
import { AccountDetailedModel } from '../../model/account.detailed.model';
import { MotionModel } from '../../model/motion.model';

@Component({
	templateUrl: './account.component.html',
	styleUrls: ['./account.component.scss'],
	selector: 'account'
})
export class AccountComponent {
	public motions?: MotionModel[];
	public newMotion: MotionModel;
	public form!: UntypedFormGroup;
	@Input('account') account!: AccountDetailedModel;
	@Input('active') active: boolean = false;
	@Input() reloadEvent!: Observable<string[]>;

	@Output() onUpdate: EventEmitter<MotionModel[]> = new EventEmitter<MotionModel[]>();

	constructor(
		private fb: UntypedFormBuilder,
		private httpClient: HttpClient,
		private activatedRoute: ActivatedRoute
	) {
		this.newMotion = {
			date: new Date(),
			plus: 0,
			minus: 0,
		};
	}

	ngOnInit(): void {
		this.form = this.fb.group({
			dateFrom: [
				moment(new Date).add(-7, 'days').toDate(),
				[Validators.required],
			],
			dateTo: [
				new Date,
				[Validators.required],
			],
		});
		this.loadMotions();

		this.reloadEvent.subscribe(x => {
			if (x.find(x => x === this.account.account.id)) {
				this.loadMotions();
			}
		});
	}

	onSubmitClick() {
	}

	handlerOnAdd(motions: MotionModel[]) {
		this.onUpdate?.emit(motions.filter(x => x.accountId !== this.account.account!.id));
		this.loadMotions();

		this.httpClient
			.get<AccountDetailedModel>(ApiRoutes.Account.replace(':id', this.account.account!.id!))
			.subscribe(data => {
				this.account = data;
			});
	}

	handlerOnDelete(motion: MotionModel) {
		const index = this.motions!.findIndex(x => x.id === motion.id);
		this.motions!.splice(index, 1);
	}

	private loadMotions() {
		var url = ApiRoutes.Motions.replace(':id', this.account.account.id!);
		url += '?from=' + moment(this.form.value.dateFrom).format('yyyy-MM-DD');
		url += '&to=' + moment(this.form.value.dateTo).format('yyyy-MM-DD');

		this.activatedRoute.params.subscribe(params => {
			this.httpClient
				.get<MotionModel[]>(url)
				.subscribe(data => {
					this.motions = data;
				});
		});
	}

	afterExpand() {
		var refresh = window.location.protocol + "//";
		refresh += window.location.host;
		refresh += window.location.pathname;
		refresh += window.location.hash;
		var idx = refresh.indexOf('/account/');
		if (idx > -1) {
			refresh = refresh.substr(0, idx);
		}
		refresh += '/account/' + this.account.account.id;
		window.history.pushState({ path: refresh }, '', refresh);
	}
}
