import { Injectable, Inject, inject } from '@angular/core';
import { DOCUMENT } from '@angular/common';
import { Meta } from '@angular/platform-browser';
import { env } from '../../../environments/environment';

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

  private loaded:boolean = false;
  private base_href: any;
  private api_url: any;

  constructor(@Inject(DOCUMENT) private document: Document, @Inject(Meta) private meta: Meta) {}

  private lazyLoad(){
    if(this.loaded)
      return;

    this.base_href = this.document!.querySelector('base')?.getAttribute('href') || '/';
    this.api_url = (this.meta!.getTag('name="api-url"')?.content ?? env.default_api_url);
    this.loaded = true;
  }  

  getBaseHref(): string {
    this.lazyLoad()
    return this.base_href;
  }

  getApiUrl(route: string = ""): string {
    this.lazyLoad()
    return this.api_url + route;
  }

  readonly apiRoute = {
    user: this.getApiUrl(env.routes.user),
    group: this.getApiUrl(env.routes.group),
    module: this.getApiUrl(env.routes.module),
    moduleOfUser: this.getApiUrl(env.routes.moduleOfUser),
    groupOfUser: this.getApiUrl(env.routes.groupOfUser),
    userRep: this.getApiUrl(env.routes.userRep),
    dirGroup: this.getApiUrl(env.routes.dirGroup),
    dirUser: this.getApiUrl(env.routes.dirUser),
    directory: this.getApiUrl(env.routes.directory),
    login: this.getApiUrl(env.routes.login),
    logout: this.getApiUrl(env.routes.logout),
    loginCheck: this.getApiUrl(env.routes.loginCheck)
  };
}