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

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

  lastKey?: string;

  lastType: string;

  onLangChange: Subscription;

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

  updateValue(key: string, type: string): void {
    this.value = this.thingTranslate.getPropertyName(type as SCThingType, key);
  }

  transform<K extends string, Q extends keyof Extract<SCThings, {type: K}>>(query: Q, type: K): string;
  transform<T extends SCThings, K extends keyof T>(query: K, thing: T): string;
  transform(query: string, thingOrType: string): string;
  transform(query: unknown, thingOrType: SCThings | string | unknown): unknown {
    if (typeof query !== 'string' || query.length <= 0) {
      return query;
    }

    if (!isThing(thingOrType) && typeof thingOrType !== 'string') {
      throw new SyntaxError(
        `Wrong parameter in ThingTranslatePipe. Expected a valid SCThing or String, received: ${thingOrType}`,
      );
    }

    // store the params, in case they change
    this.lastKey = query;
    this.lastType = typeof thingOrType === 'string' ? thingOrType : thingOrType.type;

    this.updateValue(query, this.lastType);

    // 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, this.lastType);
        }
      });
    }

    return this.value;
  }

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

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