import axios, { AxiosRequestConfig } from 'axios';
import { CachingService } from "./CachingService";

export class ImportExportService {
    private baseUrl: string = '';
    private _axiosRequestConfig: AxiosRequestConfig;
    private config: any = require('../config.json');
    constructor() {
        let cachingService: CachingService = new CachingService();
        this._axiosRequestConfig = {

            headers: {
                'Content-Type': 'application/json',
                'TenantId': cachingService.read('TenantId'),
                'Language': cachingService.readPersistant('Language'),
                'Bearer': cachingService.read('Token'),
                'UserId': cachingService.read('UserId')
            }
        };
        this.baseUrl = this.config.baseUrl;
    }

    downloadFile(recordId: number, entityId: number, fileName: string): Promise<void> {
        return this._getFileFromServer(recordId, entityId).then((url) => {
            const link = document.createElement('a');
            link.href = url;

            link.setAttribute('download', fileName + '.pdf'); //or any other extension
            document.body.appendChild(link);
            link.click();
        }, (error: any) => {
            alert(error);
        });
    }

    showFile(recordId: number, entityId: number): Promise<void> {
        return this._getFileFromServer(recordId, entityId).then((url) => {
            //window.open(url, 'file.pdf');
            const link = document.createElement('a');
            link.href = url;
            //link.setAttribute('download', 'file.pdf'); //or any other extension
            document.body.appendChild(link);
            link.click();
        }, (error: any) => {
            alert(error);
        });;
    }

    _getFileFromServer(recordId: number, entityId: number): Promise<string> {
        return new Promise((resolve, reject) => {
            this._axiosRequestConfig.responseType = 'blob';
            axios.get(this.baseUrl + '/api/AAAID/ExportDocument?recordId=' + recordId + '&entityId='+ entityId, this._axiosRequestConfig).then((response) => {

                const url = window.URL.createObjectURL(new Blob([response.data]));
                resolve(url);
            }, (err) => {
                reject(err);
            });
        });
    }
}