/**
 * This file is part of Anis Client.
 *
 * @copyright Laboratoire d'Astrophysique de Marseille / CNRS
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

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

import { Observable } from 'rxjs';

import { AppConfigService } from 'src/app/app-config.service';

declare var samp: any;

/**
 * @class
 * @classdesc Samp service.
 */
@Injectable()
export class SampService {
    private connector = null;
    
    constructor(private config: AppConfigService) {
        const baseUrl = window.location.protocol + "//" + window.location.host + this.config.baseHref;
        const meta = {
            "samp.name": "ANIS",
            "samp.description.text": "AstroNomical Information System",
            "author.email": "cesamsi@lam.fr",
            "author.affiliation": "CeSAM, Laboratoire d'Astrophysique de Marseille",
            "home.page": "https://anis.lam.fr",
            "samp.icon.url": baseUrl + "/assets/cesam_anis40.png"
        };
        this.connector = new samp.Connector("anis-client", meta);
    }

    /**
     * Register to Samp.
     *
     * @return Observable<any>
     */
    register(): Observable<any> {
        return new Observable(observer => {
            samp.register(this.connector.name, (conn) => {
                this.connector.setConnection(conn);
                observer.next(true);
                observer.complete();
            }, () => {
                observer.error(new Error('Oups!'));
                observer.complete();
            });
        });
    }

    /**
     * Disconnect to Samp.
     *
     * @return Observable<any>
     */
    unregister(): void {
        this.connector.unregister();
    }

    /**
     * Disconnect to Samp.
     *
     * @param  {string} mtype - Message type.
     * @param  {string} url - URL.
     */
    broadcast(mtype: string, url: string): void {
        const message = new samp.Message(mtype, {"url": encodeURI(url)});
        this.connector.connection.notifyAll([message]);
    }
}