import {Injectable} from "@angular/core";
import {HttpClient, HttpHeaders} from "@angular/common/http";
import {properties} from "../../../environments/environment";
import {CustomOptions} from "./servicesUtils/customOptions.class";

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

  constructor(private http: HttpClient) {}


  clearCache(message: string = null, url:string = null) {
    if(properties.deleteCacheUrl) {
      this.http.get(properties.deleteCacheUrl + (url?'?url='+url:'')).subscribe(
        res => console.log((message ? message + ": " : "") + "Cache cleared!"),
        err => console.log((message ? message + ": " : "") + "Cache could not be cleared ", err)
      );
    }
  }
  clearCacheInRoute(message: string = null, pid:string, route:string = "/") {
    let domain = "";
    if(properties.environment == 'production' || properties.environment == 'beta') {
      domain = 'https://' + (properties.environment == 'production' ? '' : 'beta.') + pid + '.openaire.eu';
    }
    domain = properties.connectPortalUrl;
    this.http.get(domain + route + '?forceCacheReload=true',
      {
        headers: new HttpHeaders({
          'Cache-Control': 'no-cache, no-store, must-revalidate',
          'Pragma': 'no-cache',
          'Expires': '0',
        })
      }).subscribe(
      res => console.log((message ? message + ": " : "") + "Cache cleared!"),
      err => console.log((message ? message + ": " : "") + "Cache could not be cleared ", err)
    );

  }

  purgeBrowserCache(message: string = null, pid: string) {
    if(properties.deleteBrowserCacheUrl) {
      let url = properties.deleteBrowserCacheUrl + "/" + pid;
      this.http.get(url, CustomOptions.registryOptions()).subscribe(
        res => console.log((message ? message + ": " : "") + "Browser Cache purged!"),
        err => console.log((message ? message + ": " : "") + "Browser Cache could not be purged ", err)
      );
    }
  }
}
