import {Injectable} from '@angular/core';
import {StorageProvider} from '../storage/storage.provider';
import {ConfigProvider} from '../config/config.provider';
import {ModalController} from '@ionic/angular/standalone';
import {Capacitor} from '@capacitor/core';
import {ReleaseNotesComponent} from './release-notes.component';
import {SCAppVersionInfo} from '@openstapps/core';
import {App} from '@capacitor/app';
import {coerce} from 'semver';

export const RELEASE_NOTES_SHOWN_KEY = 'release_notes_shown';

@Injectable({providedIn: 'root'})
export class AppVersionService {
  constructor(
    private storage: StorageProvider,
    private config: ConfigProvider,
    private modalController: ModalController,
  ) {}

  /**
   * Get the latest release notes that have not been presented yet
   */
  async getPendingReleaseNotes() {
    if (Capacitor.getPlatform() === 'web') {
      return;
    }
    const currentVersion = coerce(await App.getInfo().then(info => info.version))!;
    if (!(await this.storage.has(RELEASE_NOTES_SHOWN_KEY))) {
      await this.storage.put(RELEASE_NOTES_SHOWN_KEY, currentVersion);
    }
    const storedVersion = coerce(await this.storage.get<string>(RELEASE_NOTES_SHOWN_KEY))!;

    return this.config.config.app.versionHistory
      ?.filter(({version}) => {
        const semanticVersion = coerce(version)!;
        const wasNotShown = semanticVersion.compare(storedVersion) === 1;
        const isNotFutureVersion = semanticVersion.compare(currentVersion) <= 0;
        return wasNotShown && isNotFutureVersion;
      })
      ?.sort((a, b) => -coerce(a.version)!.compare(b.version));
  }

  /**
   * Present release notes
   */
  async presentReleaseNotes(versions: SCAppVersionInfo[]) {
    if (!versions || versions.length === 0) {
      return;
    }
    const modal = await this.modalController.create({
      component: ReleaseNotesComponent,
      componentProps: {
        versionInfos: versions,
      },
    });
    await modal.present();
    await modal.onDidDismiss();
    await this.storage.put(RELEASE_NOTES_SHOWN_KEY, versions[0].version);
  }
}
