import { Component, Input, OnChanges }  from '@angular/core';
import { Http }                         from '@angular/http';

import { HelperService }                from '../../../../services/svc.helper'

import { Observable }                   from 'rxjs/Observable';
import 'rxjs/add/observable/of';
import 'rxjs/add/operator/mapTo';
import 'rxjs/add/operator/toPromise';

@Component({
    moduleId: module.id+ '',
    selector: 'downloads',
    templateUrl: './tpl.downloads.pug',
    styleUrls: ['./sty.downloads.scss']
})

export class DownloadsComponent implements OnChanges {

    mockAttributes: any = [];
    mockSpecSheets: any = [];
    mockGlobals: any = [];

    checkAssemblySheet: any = false;
    checkSpecSheets: any = false;
    @Input('attributes') attributes:any;
    @Input('sku') sku:string;

    files = [];

    constructor(
        private _helper: HelperService,
        private http: Http
    ) {}

    server: string = this._helper.server

    ngOnChanges(): void {

        // Checks assmbly sheet and spec sheet exists before rendering
        this.checkAssemblySheet = this.file_exists(this.server + 'pub/media/files/' + this._helper.storeCode + '/assembly/' + this.clean(this.sku) + '.pdf')
        this.checkSpecSheets = this.file_exists(this.server + 'pub/media/files/' + this._helper.storeCode + '/specsheets/' + this.clean(this.sku) + '.pdf')
       
        // Find the active files attribute
        for(let attribute of this.attributes) {
            if(attribute.code.indexOf('files') > 0) {
                console.log(attribute)

                this.files = attribute.formattedValue.split(',')


            }
        }
    }

    // Removes Aa-Zz - (A+B+S) from string
    clean(string: string) {
        return string.replace(/([^0-9,A,B,S])/g, '')
    }

    // Maps if file exists from the http.head and returns true/false based on response
    file_exists(path: string): Promise<boolean> {
        return this.http.head(path)
        .mapTo(true)
        .catch((error) => Observable.of(false))
        .toPromise()
    }
}