/*
 * 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 {Injectable, OnDestroy, Pipe, PipeTransform} from '@angular/core';
import {TranslateService} from '@ngx-translate/core';
import {isThing, SCThings, SCThingWithoutReferences} from '@openstapps/core';
import {Subscription} from 'rxjs';
import {ThingTranslateService} from './thing-translate.service';

@Injectable()
@Pipe({
  name: 'thingTranslate',
  pure: false, // required to update the value when the promise is resolved
})
export class ThingTranslatePipe implements PipeTransform, OnDestroy {
  value: unknown;

  lastKey?: string;

  lastThing: SCThingWithoutReferences;

  onLangChange: Subscription;

  constructor(
    private readonly translate: TranslateService,
    // private readonly _ref: ChangeDetectorRef,
    private readonly thingTranslate: ThingTranslateService,
  ) {}

  updateValue(key: string, thing: SCThingWithoutReferences): void {
    this.value = this.thingTranslate.get(thing as SCThings, key);
  }

  transform<T extends SCThingWithoutReferences, P extends string[] | string | keyof T>(
    query: P,
    thing: T,
  ): P extends keyof T ? T[P] : P | unknown {
    if (typeof query !== 'string' || query.length <= 0) {
      return query as never;
    }

    if (!isThing(thing)) {
      throw new SyntaxError(
        `Wrong parameter in ThingTranslatePipe. Expected a valid SCThing, received: ${thing}`,
      );
    }

    // store the params, in case they change
    this.lastKey = query;
    this.lastThing = thing;

    this.updateValue(query, thing);

    // if there is a subscription to onLangChange, clean it
    this._dispose();

    if (this.onLangChange?.closed ?? true) {
      this.onLangChange = this.translate.onLangChange.subscribe(() => {
        if (typeof this.lastKey === 'string') {
          this.lastKey = undefined; // we want to make sure it doesn't return the same value until it's been updated
          this.updateValue(query, thing);
        }
      });
    }

    return this.value as never;
  }

  /**
   * Clean any existing subscription to change events
   */
  private _dispose(): void {
    if (this.onLangChange?.closed) {
      this.onLangChange?.unsubscribe();
    }
  }

  ngOnDestroy(): void {
    this._dispose();
  }
}
