/*
 * Copyright (C) 2023 StApps
 * This program is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation, version 3.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <https://www.gnu.org/licenses/>.
 */
import {DestroyRef, Directive, ElementRef, inject, Input, OnInit, Renderer2} from '@angular/core';
import {AnimationController, NavController} from '@ionic/angular/standalone';
import {Router, RouterEvent} from '@angular/router';
import {tabsTransition} from './tabs-transition';
import {takeUntilDestroyed} from '@angular/core/rxjs-interop';

@Directive({
  selector: '[rootLink]',
})
export class RootLinkDirective implements OnInit {
  @Input() rootLink: string;

  @Input() redirectedFrom: string;

  private readonly classNames = ['tab-selected', 'link-active'];

  private needsInit = true;

  destroy$ = inject(DestroyRef);

  constructor(
    private element: ElementRef,
    private renderer: Renderer2,
    private navController: NavController,
    private router: Router,
    private animationController: AnimationController,
  ) {}

  ngOnInit() {
    const animation = tabsTransition(this.animationController);
    this.renderer.setAttribute(this.element.nativeElement, 'button', '');
    if (document.querySelector('#main')?.childNodes.length === 1) {
      if (this.router.url === this.rootLink) {
        this.setActive();
      }
      this.needsInit = false;
    }

    this.router.events.pipe(takeUntilDestroyed(this.destroy$)).subscribe(event => {
      if (
        event instanceof RouterEvent &&
        // @ts-expect-error access private member
        (this.navController.direction === 'root' || this.needsInit)
      ) {
        if (event.url === this.rootLink || (this.redirectedFrom && event.url === this.redirectedFrom)) {
          this.setActive();
        } else {
          this.setInactive();
        }
        this.needsInit = false;
      }
    });

    this.destroy$.onDestroy(
      this.renderer.listen(this.element.nativeElement, 'click', () => {
        this.setActive();
        this.navController.setDirection('root', true, 'back', animation);
        void this.router.navigate([this.rootLink]);
      }),
    );
  }

  setActive() {
    for (const className of this.classNames) {
      this.renderer.addClass(this.element.nativeElement, className);
    }
  }

  setInactive() {
    for (const className of this.classNames) {
      this.renderer.removeClass(this.element.nativeElement, className);
    }
  }
}
