import { Injectable } from '@angular/core';
import { CookieOptions, CookieService } from 'ngx-cookie';
import { CordovaService } from './cordova.service';

@Injectable({
  providedIn: 'root',
})
export class AppCookieService {
  /**
   * On ios we have to use a custom plugin, because the wkwebview can not use
   * cookies via js (its an ios bug)
   */
  private usePlugin: boolean = false;

  constructor(private cookieService: CookieService, private cordovaService: CordovaService) {
    this.usePlugin =
      this.cordovaService.isOnApp() && this.cordovaService.getDevicePlatform() == 'iOS';
  }

  public get(name: string): Promise<string> {
    if (this.usePlugin) {
      return window['blobSaver'].getCookies().then((cookies) => {
        return cookies[name];
      });
    } else {
      return Promise.resolve(this.cookieService.get(name));
    }
  }

  public put(name: string, value: string, options: CookieOptions): Promise<void> {
    if (this.usePlugin) {
      return window['blobSaver'].setCookie(name, value, options.expires);
    } else {
      return Promise.resolve(this.cookieService.put(name, value, options));
    }
  }

  public remove(name: string): Promise<void> {
    if (this.usePlugin) {
      return window['blobSaver'].removeCookie(name);
    } else {
      return Promise.resolve(this.cookieService.remove(name));
    }
  }
}
