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

// libs
import { Subject } from 'rxjs';

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

@Component({
	templateUrl: './account.list.component.html',
	styleUrls: ['./account.list.component.scss'],
})
export class AccountListComponent implements OnInit {
	public accounts?: AccountDetailedModel[];
	public category = '';
	public activeAccount = '';

	reloadSubject: Subject<string[]> = new Subject<string[]>();
	private readonly destroyRef = inject(DestroyRef);

	constructor(
		private httpClient: HttpClient,
		private activatedRoute: ActivatedRoute,
		private accountCategoryService: AccountCategoryService,
	) {
		this.activatedRoute.params
			.pipe(takeUntilDestroyed(this.destroyRef))
			.subscribe(x => this.activeAccount = x['accountId']);
	}

	ngOnInit(): void {
		this.activatedRoute.params
			.pipe(takeUntilDestroyed(this.destroyRef))
			.subscribe(params => {
				var categoryId = params['id'];

				this.httpClient
					.get<AccountDetailedModel[]>(ApiRoutes.Accounts + '?category=' + categoryId)
					.pipe(takeUntilDestroyed(this.destroyRef))
					.subscribe(data => {
						this.accounts = data;
					});
				this.accountCategoryService
					.getCategory(categoryId)
					.pipe(takeUntilDestroyed(this.destroyRef))
					.subscribe(data => {
						this.category = data.name!;
					});
			});
	}

	handlerOnUpdate(motions: MotionModel[]) {
		this.reloadSubject.next(motions.map(x => x.accountId!));
	}
}
