/*
 * 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, inject, Injectable, Pipe, PipeTransform} from '@angular/core';
import {TranslateService} from '@ngx-translate/core';
import {get} from '@openstapps/collection-utils';
import {Subscription} from 'rxjs';
import {takeUntilDestroyed} from '@angular/core/rxjs-interop';

@Injectable()
@Pipe({
  name: 'translateSimple',
  pure: false,
})
export class TranslateSimplePipe implements PipeTransform {
  value: unknown;

  query: unknown;

  thing: unknown;

  onLangChange: Subscription;

  destroy$ = inject(DestroyRef);

  constructor(private readonly translate: TranslateService) {}

  // eslint-disable-next-line @typescript-eslint/ban-types
  private updateValue() {
    try {
      this.value =
        get(
          // eslint-disable-next-line @typescript-eslint/no-explicit-any
          (this.thing as any).translations[this.translate.currentLang] ?? this.thing,
          this.query as string,
        ) ?? this.thing;
    } catch (error) {
      console.warn(`${this.query}: ${error}`);
      this.value = this.thing;
    }
  }

  transform<T extends object, P extends keyof T>(query: P, thing: T): T[P];
  transform<T extends object, P extends string | string[]>(query: P, thing: T): P | unknown {
    // store the params, in case they change
    this.query = query;
    this.thing = thing;

    this.updateValue();

    this.onLangChange ??= this.translate.onLangChange
      .pipe(takeUntilDestroyed(this.destroy$))
      .subscribe(() => {
        this.updateValue();
      });

    return this.value as never;
  }
}
