/**
 * 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 { Component, EventEmitter, Input, Output } from '@angular/core';
import { HttpClient } from '@angular/common/http';

import { Criterion, ConeSearch, criterionToString } from '../../../store/models';
import { Dataset } from 'src/app/metamodel/models';
import { getHost as host } from 'src/app/shared/utils';
import { AppConfigService } from 'src/app/app-config.service';

/**
 * @class
 * @classdesc Search result download component.
 */
@Component({
    selector: 'app-download',
    templateUrl: 'download.component.html'
})
export class DownloadComponent {
    @Input() datasetSelected: string;
    @Input() datasetList: Dataset[];
    @Input() criteriaList: Criterion[];
    @Input() outputList: number[];
    @Input() coneSearch: ConeSearch;
    @Input() dataLength: number;
    @Input() sampRegistered: boolean;
    @Output() broadcast: EventEmitter<string> = new EventEmitter();

    constructor(private appConfig: AppConfigService, private http: HttpClient) { }

    /**
     * Checks if download tab has to be display.
     *
     * @return boolean
     */
    isDownloadActivated(): boolean {
        const dataset = this.datasetList.find(d => d.name === this.datasetSelected);
        return dataset.config.download.download_enabled;
    }

    /**
     * Checks if download tab has to be open.
     *
     * @return boolean
     */
    isDownloadOpened(): boolean {
        const dataset = this.datasetList.find(d => d.name === this.datasetSelected);
        return dataset.config.download.download_opened;
    }

    /**
     * Checks if the download format is allowed by Anis Admin configuration.
     *
     * @param  {string} format - The file format to download.
     *
     * @return boolean
     */
    getConfigDownloadResultFormat(format: string): boolean {
        const dataset = this.datasetList.find(dataset => dataset.name === this.datasetSelected);
        return dataset.config.download[format];
    }

    /**
     * Returns URL to download file for the given format.
     *
     * @param  {string} format - The file format to download.
     *
     * @return string
     */
    getUrl(format: string): string {
        let query: string = host(this.appConfig.apiUrl) + '/search/' + this.datasetSelected + '?a=' + this.outputList.join(';');
        if (this.criteriaList.length > 0) {
            query += '&c=' + this.criteriaList.map(criterion => criterionToString(criterion)).join(';');
        }
        if (this.coneSearch) {
            query += '&cs=' + this.coneSearch.ra + ':' + this.coneSearch.dec + ':' + this.coneSearch.radius;
        }
        query += '&f=' + format
        return query;
    }

    /**
     * Returns URL to download archive.
     *
     * @return boolean
     */
    getUrlArchive(): string {
        let query: string = host(this.appConfig.apiUrl) + '/archive/' + this.datasetSelected + '?a=' + this.outputList.join(';');
        if (this.criteriaList.length > 0) {
            query += '&c=' + this.criteriaList.map(criterion => criterionToString(criterion)).join(';');
        }
        if (this.coneSearch) {
            query += '&cs=' + this.coneSearch.ra + ':' + this.coneSearch.dec + ':' + this.coneSearch.radius;
        }
        return query;
    }

    /**
     * Emits event to  action to broadcast data.
     *
     * @fires EventEmitter<string>
     */
    broadcastVotable(): void {
        this.broadcast.emit(this.getUrl('votable'));
    }

    /**
     * Allows to download file.
     */
    click(event, href, extension): void {
        event.preventDefault();

        this.http.get(href, {responseType: "blob"}).subscribe(
            data => {
                let downloadLink = document.createElement('a');
                downloadLink.href = window.URL.createObjectURL(data);
                downloadLink.setAttribute('download', `${this.datasetSelected}.${extension}`);
                downloadLink.click();
            }
        );
    }
}