// angular
import { Component, DestroyRef, inject } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { Input } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { ActivatedRoute } from '@angular/router';
import { Output } from '@angular/core';
import { EventEmitter } from '@angular/core';

// libs
import 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 dateFrom: Date = moment(new Date).add(-7, 'days').toDate();
	public dateTo: Date = moment(new Date).add(0, 'days').toDate();
	@Input('account') account!: AccountDetailedModel;
	@Input('active') active: boolean = false;
	@Input() reloadEvent!: Observable<string[]>;

	@Output() onUpdate: EventEmitter<MotionModel[]> = new EventEmitter<MotionModel[]>();
	private readonly destroyRef = inject(DestroyRef);

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

	ngOnInit(): void {
		this.loadMotions();

		this.reloadEvent
			.pipe(takeUntilDestroyed(this.destroyRef))
			.subscribe(x => {
				if (x.find(id => id === 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!))
			.pipe(takeUntilDestroyed(this.destroyRef))
			.subscribe(data => {
				this.account = data;
			});
	}

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

	onChangePeriod(dates: Date[]) {
		this.dateFrom = dates[0];
		this.dateTo = dates[1];
		this.loadMotions();
	}

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

		this.httpClient
			.get<MotionModel[]>(url)
			.pipe(takeUntilDestroyed(this.destroyRef))
			.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);
	}
}
