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

@Injectable({
  providedIn: 'root'
})
export class CookieService {
  constructor() { }

  set(key:string, value:string, expires?:Date):void {
    let cookieValue = `${key}=${value}`;
    if (expires) cookieValue += `;expires='${expires.toUTCString()}';path=/`;
    document.cookie = cookieValue;
  }

  delete(key:string) {
    const date = new Date();
    date.setTime(date.getTime() - 10000);
    document.cookie = `${key}=a; expires=${date.toUTCString()}`;
  }

  get(key:string):string {
    const decodedCookie:string = decodeURIComponent(document.cookie);
    const pairs:string[] = decodedCookie.split(/;\s*/);

    const prefix = `${key}=`;
    for (const pair of pairs) {
      if (pair.indexOf(prefix) == 0) {
        return pair.substring(prefix.length);
      }
    }
    return '';
  }
}
