import { Injectable } from '@angular/core';
import { LocalNotifications, ILocalNotification } from '@ionic-native/local-notifications/ngx';

export interface UserLocalData {
  [key: string]: any;
}

@Injectable({
  providedIn: 'root'
})

export class UserLocalNotificationService {

  public static STORAGE_KEY = 'notifications';
  constructor(
    public localNotification: LocalNotifications,
  ) { }

  public async requestNotificationPermission(): Promise<boolean> {
    const hasPermission = await this.checkNotificationPermission();
      if (!hasPermission) {
        return await this.localNotification.requestPermission();
      } else {
        return true;
      }
  }

  public async checkNotificationPermission(): Promise<boolean> {
    return await this.localNotification.hasPermission();
  }

  public async cancelCategoryNotifications(category: string) {
    const notifications = await this.localNotification.getAll();
    for (const notification of notifications) {
      const parsedData = JSON.parse(notification.data);
      const notifCategory = parsedData['category'];
      if (notifCategory === category) {
        await this.localNotification.cancel(notification.id);
      }
    }
  }

  public async isCategoryExist(category: string) {
    const notifications = await this.localNotification.getAll();
    for (const notification of notifications) {
      const parsedData = JSON.parse(notification.data);
      const notifCategory = parsedData['category'];
      // alert( 'notifCategory:' + notifCategory + ' category:' + category);
      if (notifCategory === category) {
        return true;
      }
    }
    return false;
  }

  public createNotification(title: string, text: string, date: Date,
    category: string) {
    const notifID = this.generateNotificationID();
    this.scheduleNotification(notifID, title, text, date, category);
  }

  private scheduleNotification(notifId: number, title: string, text: string,
    date: Date, category: string) {
    this.localNotification.on('click').subscribe(notification => {
      this.localNotification.clear(notification.id);
    });
    this.localNotification.schedule({
      id: notifId,
      title: title,
      text: text,
      trigger: {at: date},
      data : {'category': category},
    });
  }

  public deleteAllNotifications() {
    this.localNotification.clearAll();
    this.localNotification.cancelAll();
  }

  public cancelNotification(notifID: number) {
    this.localNotification.cancel(notifID);
  }

  public clearTriggeredNotifications() {
    this.localNotification.clearAll();
  }

  private generateNotificationID(): number {
    return Date.now() + Math.floor(Math.random() * (1000 - 1) + 1);
  }

  public async getNotifications(): Promise<ILocalNotification[]> {
    const notifs = await this.localNotification.getAll();
    return notifs;
  }
}
