import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class CookiesHelper {
  public static getCookie(name: string) {
    const c = document.cookie.match('(^|[^;]+)\\s*' + name + '\\s*=\\s*([^;]+)');
    return c ? c.pop() : '';
  }

  public static setCookie(
    name: string,
    value: any,
    days: number,
    expireAt=null,
    expireAtBrowserClose=false,
    sameSiteValue: string = null,
  ) {
    let expires = '';
    if (expireAtBrowserClose) {
      expires = '; expires=Session';
    } else if (expireAt) {
      expires = '; expires=' + expireAt;
    } else if (days) {
      const date = new Date();
      date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
      expires = '; expires=' + date.toUTCString();
    }
    let cookie = `${name}=${value || ''}${expires}; path=/`;
    if (sameSiteValue) {
      cookie += `; SameSite=${sameSiteValue}`;
    }
    document.cookie = cookie;
  }

  public static clearCookie(name: string) {
    const date = new Date();
    date.setTime(date.getTime() + (-1 * 24 * 60 * 60 * 1000));
    const expires = '; expires=' + date.toUTCString();
    document.cookie = `${name}=${expires}; path=/; SameSite=Lax`;
  }
}
