import { DOCUMENT } from '@angular/common';
import { Inject, Injectable } from '@angular/core';

@Injectable({
    providedIn: 'root',
})
export class CanonicalService {
    constructor(@Inject(DOCUMENT) private DOM) {}

    updateURL(type: 'fullURL' | 'baseURL') {
        const canonicalURL = type === 'fullURL' ? this.DOM.URL : this.getBaseUrl();
        const currentLink = this.getCanonicalLink();

        currentLink ? currentLink.setAttribute('href', canonicalURL) : this.DOM.head.appendChild(this.createCanonicalLink(canonicalURL));
    }

    getUrl(): string {
        const link = this.getCanonicalLink();
        return link ? link.getAttribute('href') : null;
    }

    getBaseUrl(): string {
        const onlineboardRegex = /[\w\W]*\/onlineboard\//;
        const scheduleRegex = /[\w\W]*\/schedule\//;

        const fullURL: string = this.DOM.URL;
        const baseUrl: string = fullURL.match(onlineboardRegex)?.[0] || fullURL.match(scheduleRegex)?.[0];

        return baseUrl;
    }

    private getCanonicalLink(): HTMLLinkElement | null {
        return this.DOM.head.querySelector('link[rel="canonical"]');
    }

    private createCanonicalLink(url: string): HTMLLinkElement {
        const link: HTMLLinkElement = this.DOM.createElement('link');
        link.setAttribute('rel', 'canonical');
        link.setAttribute('href', url);

        return link;
    }
}
