import { Component, OnInit } from '@angular/core';
import { ApiService } from '../../app.api.service'
import { FileInfo, UploadEvent, SelectEvent, SuccessEvent, RemoveEvent, ErrorEvent, FileRestrictions } from '@progress/kendo-angular-upload';
import { UploadFile } from '../../_models/common/uploadFile';
import { DropDownsModule } from '@progress/kendo-angular-dropdowns';
import { SystemConfigurationService } from '../../_services/common/systemconfiguration.service';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { EnumConfigurationType, EnumExtension } from '../../_models/enums';
import { UntilityHandlerService } from '../../utility.hanldler.service';
import { HRMNotificationService } from '../../app.notification.service';
import { loadingPanelService } from '../../hrm-loding panel/loding.panel.service';
import * as fileSaver from 'file-saver';
@Component({
    selector: 'app-system-configuration',
    templateUrl: './system-configuration.component.html',
    styleUrls: ['./system-configuration.component.css']
})
export class SystemConfigurationComponent implements OnInit {
   private _kendoFiles: FileInfo[];

    uploadSaveUrl = '';
    uploadRemoveUrl = '';
    filename: string;

    myFiles: Array<FileInfo> = [];
    allFiles: Array<FileInfo> = [];
    myfile: FileInfo;
    name: string;
    size: number;
    fileTypeid: number;


    public uploadAttachment: UploadFile[] = [];

    public uploadFile: UploadFile;
    public count = 0;
    public successCount = 0;
    public originalName: string;
    public filedlName: string;
    subscribers: any = {};
    private _filesSet: Set<File>;
    public fileRestrictions: FileRestrictions = {
        allowedExtensions: ['.xml']
    };

    public seletedFiles: Array<File>;
    _fromValidator: FormGroup;
    selectedFiles?: FileList;

    configtypes: any = EnumExtension.getNamesAndValues(EnumConfigurationType);

    constructor(public systemConfigService: SystemConfigurationService,
        public apiService: ApiService, public utilityHandlerService: UntilityHandlerService,
        public notificationService: HRMNotificationService, public loadingPanelService: loadingPanelService) {

        this.apiService.selectedMenuName="System Configuration"
        this.uploadSaveUrl = apiService.base_url + '/filemanager/uploadConfiurationfile';
        this.uploadRemoveUrl = apiService.base_url + '/filemanager/uploadConfiurationfile';

     //   this.systemConfigService.UpdateConfiguration(EnumConfigurationType.Logic);
    }


    ngOnInit() {

        this.loadingPanelService.ShowLoadingPanel = false;
        this.createForm();
    }
    public createForm() {
        this._fromValidator = new FormBuilder().group({
            filetype: ['', Validators.required],
            filerequired: ['', Validators.required],
        });

    }
    //uploadEventHandler(e: UploadEvent) {
    //    console.log('Upload event: ', e);
    //    this._kendoFiles = e.files;
    //    this._filesSet = new Set<File>();

    //    for (var i = 0; i < this._kendoFiles.length; i++) {

    //        let rawFile: File = this._kendoFiles[i].rawFile;
    //        this._filesSet.add(rawFile);

    //    }
    //    this.upload(this._filesSet); //manualy post form data

    //    //e.preventDefault(); //comment this in to see how files sent automatially aren't catched by api controller
    //}
    download() {
        //  const data: Blob = new Blob([buffer], { type: EXCEL_TYPE });
        //  fileSaver.saveAs(data, '');
        if (this.fileTypeid == undefined) {
            this.notificationService.showWarning("select a configuration type");
            return;
        }
        var filename: string;

        if (this.fileTypeid == EnumConfigurationType.Logic) {
            filename = "Logic"
        }
        else if (this.fileTypeid == EnumConfigurationType.Menu) {
            filename = "Menu"
        }
        else if (this.fileTypeid == EnumConfigurationType.UI) {
            filename = "UI"
        }
        else {
            this.notificationService.showWarning("select a configuration type.");
            return;
        }

        this.loadingPanelService.ShowLoadingPanel = true;

        this.systemConfigService.getConfigXmlFile(this.fileTypeid).subscribe(
            (filedata) => {
                const data: Blob = new Blob([filedata], { type: 'xml' });
                fileSaver.saveAs(data, filename + '.xml');
            },
            (err) => {
                this.loadingPanelService.ShowLoadingPanel = false;
                this.notificationService.showError(err.error);
            },
            () => {
                this.loadingPanelService.ShowLoadingPanel = false;
                this.notificationService.showSuccess("Data downloded successfully.")
            });
    }


    public upload() {

        if (this.fileTypeid == undefined) {
            this.notificationService.showWarning("select a configuration type");
            return;
        }
        if (this.selectedFiles.length > 0) {
            const file: File | null = this.selectedFiles.item(0);
                const formData: FormData = new FormData();
            formData.append('confile', file);
            formData.append('fileTypeid', String(this.fileTypeid));
                this.loadingPanelService.ShowLoadingPanel = true;
                this.systemConfigService.uploadConfigFile(formData).subscribe(
                    (data) => {

                    },
                    (err) => {
                        this.loadingPanelService.ShowLoadingPanel = false;
                        this.notificationService.showError(err.error);
                    },
                    () => {
                        this.loadingPanelService.ShowLoadingPanel = false;
                        this.notificationService.showSuccess("Data uploaded successfully.")
                    });

        }
    }



    successEventHandler1(e: SuccessEvent) {
        this.uploadFile = new UploadFile();
        if (e.operation == 'upload') {

            if (e.response) {
                const response1 = e.response.body;

                for (let i = 0; i < response1.length; i++) {
                    this.uploadFile = response1[i];
                    const date = new Date();
                    this.uploadFile.UploadDate = new Date(date);
                    this.uploadAttachment.push(this.uploadFile);

                    const tempFile: FileInfo = {
                        uid: this.uploadFile.GeneratedFileName,
                        name: this.uploadFile.OriginalFileName,
                        size: 0
                    };

                    this.myFiles.push(tempFile);
                }



            }
        }

    }

    removeEventHandler1(e: RemoveEvent) {
        this.filename = e.files[0].name;
        e.data = {
            attachmentType: e.files[0].name
        };
    }

    errorEventHandler1(e: ErrorEvent) {
        const fileNames: string[] = [];
        const customeError: any = e;
        let count = 0;

        for (let i = 0; i < customeError.files.length; i++) {
            if (customeError.files[i].size > 512000) {

                fileNames[count] = customeError.files[i].name;
                count++;
            }
        }
        const file = fileNames.join(',');



        if (customeError.response.error.ExceptionMessage != undefined) {
           // this.notificationService.showWarning(file + customeError.response.error.ExceptionMessage);
        }
    }

    public getFile(uid: string) {
        let tempName = '';
        let tempext = '';

        for (let i = 0; i < this.uploadAttachment.length; i++) {
            if (this.uploadAttachment[i].GeneratedFileName === uid) {
                tempName = this.uploadAttachment[i].GeneratedFileName;
                tempext = this.uploadAttachment[i].OriginalFileName.split('.').pop();

            }

        }

        const data = {
            fileName: tempName + '.' + tempext,

        };


        let tempBlob: any;

        this.apiService.httpPost('filemanager/uploadConfigurationfile/', data)
            .subscribe(x => {

                for (let i = 0; i < this.uploadAttachment.length; i++) {
                    if (this.uploadAttachment[i].GeneratedFileName === uid) {
                        this.uploadAttachment.splice(i, 1);
                    }
                }

                for (let i = 0; i < this.myFiles.length; i++) {
                    if (this.myFiles[i].uid === uid) {
                        this.myFiles.splice(i, 1);
                    }
                }


            },
                (error) => {
                //    this.notificationService.showError(error);
                }, () => {


                    //  this.downloadBlob(tempBlob);
                });

    }

    selectFile(event: any): void {

        this.selectedFiles = event.target.files;

        //if (this.selectedFiles.length > 0) {
        //    const file: File | null = this.selectedFiles.item(0);
        //    this.selectedFiles = file;
        //}
    }
    public downloadFile(uid: string): void {
        const temporiginalName = '';
        let tempName = '';
        let tempext = '';

        for (let i = 0; i < this.uploadAttachment.length; i++) {
            if (this.uploadAttachment[i].GeneratedFileName === uid) {
                tempName = this.uploadAttachment[i].GeneratedFileName;
                tempext = this.uploadAttachment[i].OriginalFileName.split('.').pop();
                this.originalName = this.uploadAttachment[i].OriginalFileName;
            }

        }
        this.filedlName = tempName + '.' + tempext;



        const data = {
            fileName: tempName + '.' + tempext,
            mappingPath: '~/Documents/' + this.filedlName
        };
        this.subscribers.fileSubscriber = this.apiService.httpPost('download/get-file-type', data).
            subscribe(
                result => {
                  //  this.contentType = ((result) as any);
                },
                error => {
                   // this.notificationService.showError(error);
                },
                () => {

                    let tempBlob: any;

                    this.apiService.httpPostFile('download/get-download-file/', data)
                        .subscribe(fileData => {

                         //   tempBlob = new Blob([fileData], { type: this.contentType });
                        },
                            (error) => {
                             //   this.notificationService.showError(error);
                            }, () => {

                                this.downloadBlob(tempBlob);
                            });
                });

    }


    downloadBlob(data: any): void {
        //const blob: Blob = new Blob([data], { type: this.contentType });
        ////  const fileName: string = this.workOrderBillReceive.UploadAttachment[0].OriginalFileName;
        //const fileName: string = this.originalName;
        //const objectUrl: string = URL.createObjectURL(blob);
        //const a: HTMLAnchorElement = document.createElement('a') as HTMLAnchorElement;

        //a.href = objectUrl;
        //a.download = fileName;
        //document.body.appendChild(a);
        //a.click();

        //document.body.removeChild(a);
        //URL.revokeObjectURL(objectUrl);
    }


}