/*
 * Copyright (C) 2018, 2019 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 {Component} from '@angular/core';
import {ActivatedRoute} from '@angular/router';
import {Network} from '@ionic-native/network/ngx';
import {IonRefresher} from '@ionic/angular';
import {LangChangeEvent, TranslateService} from '@ngx-translate/core';
import {
  SCLanguageCode,
  SCThings,
  SCUuid,
  SCSaveableThing,
} from '@openstapps/core';
import {DataProvider, DataScope} from '../data.provider';
import {FavoritesService} from '../../favorites/favorites.service';
import {take} from 'rxjs/operators';

/**
 * A Component to display an SCThing detailed
 */
@Component({
  selector: 'stapps-data-detail',
  styleUrls: ['data-detail.scss'],
  templateUrl: 'data-detail.html',
})
export class DataDetailComponent {
  /**
   * The associated item
   *
   * undefined if not loaded, null when unavailable
   */
  item?: SCThings | null = undefined;

  /**
   * The language of the item
   */
  language: SCLanguageCode;

  /**
   * Type guard for SCSavableThing
   */
  static isSCSavableThing(
    thing: SCThings | SCSaveableThing,
  ): thing is SCSaveableThing {
    return typeof (thing as SCSaveableThing).data !== 'undefined';
  }

  /**
   *
   * @param route the route the page was accessed from
   * @param dataProvider the data provider
   * @param network the network provider
   * @param favoritesService the favorites provider
   * @param translateService he translate provider
   */
  constructor(
    protected readonly route: ActivatedRoute,
    private readonly dataProvider: DataProvider,
    protected readonly network: Network,
    private readonly favoritesService: FavoritesService,
    translateService: TranslateService,
  ) {
    this.language = translateService.currentLang as SCLanguageCode;
    translateService.onLangChange.subscribe((event: LangChangeEvent) => {
      this.language = event.lang as SCLanguageCode;
    });
  }

  /**
   * Provides data item with given UID
   *
   * @param uid Unique identifier of a thing
   */
  async getItem(uid: SCUuid) {
    try {
      const item = await this.dataProvider.get(uid, DataScope.Remote);
      this.item = DataDetailComponent.isSCSavableThing(item) ? item.data : item;
    } catch {
      // eslint-disable-next-line unicorn/no-null
      this.item = null;
    }
  }

  /**
   * Check if we have internet
   */
  isDisconnected(): boolean {
    return this.network.type === this.network.Connection.NONE;
  }

  /**
   * Initialize
   */
  async ionViewWillEnter() {
    const uid = this.route.snapshot.paramMap.get('uid') || '';
    await this.getItem(uid ?? '');
    // fallback to the saved item (from favorites)
    if (this.item === null) {
      this.favoritesService
        .get(uid)
        .pipe(take(1))
        .subscribe(item => {
          if (typeof item !== undefined) {
            this.item = item;
          }
        });
    }
  }

  /**
   * Updates the shown thing
   *
   * @param refresher Refresher component that triggers the update
   */
  async refresh(refresher: IonRefresher) {
    await this.getItem(this.route.snapshot.paramMap.get('uid') ?? '');
    await refresher.complete();
  }
}
