/*
 * 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,
  Host,
  inject,
  OnInit,
  Optional,
  Self,
  ViewContainerRef,
} from '@angular/core';
import {SCIcon} from './icon';
import {IconReplacer} from './replace-util';
import {TranslateService} from '@ngx-translate/core';
import {IonBackButton} from '@ionic/angular';
import {TitleCasePipe} from '@angular/common';
import {takeUntilDestroyed} from '@angular/core/rxjs-interop';

@Directive({
  selector: 'ion-back-button',
})
export class IonBackButtonDirective extends IconReplacer implements OnInit {
  destroy$ = inject(DestroyRef);

  constructor(
    element: ElementRef,
    viewContainerRef: ViewContainerRef,
    @Host() @Self() @Optional() private ionBackButton: IonBackButton,
    private translateService: TranslateService,
    private titleCasePipe: TitleCasePipe,
  ) {
    super(element, viewContainerRef, 'shadow');
  }

  replace() {
    this.replaceIcon(this.host.querySelector('.button-inner'), {
      md: SCIcon.arrow_back,
      ios: SCIcon.arrow_back_ios,
      size: 24,
    });
  }

  async ngOnInit() {
    await super.ngOnInit();
    if (document.querySelector('ion-app[mode=ios]')) {
      this.translateService
        .stream('back')
        .pipe(takeUntilDestroyed(this.destroy$))
        .subscribe((value: string) => {
          this.ionBackButton.text = this.titleCasePipe.transform(value);
        });
    }
  }
}
