import { Component, OnInit, OnDestroy, ViewChild, Output, Input, EventEmitter } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Router, ActivatedRoute } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { tap, catchError } from 'rxjs/operators';
import { of } from 'rxjs/observable/of';
import {Http} from "@angular/http";
import {Form} from "@angular/forms";
import * as formData from 'form-data';
import {forEach} from '@angular/router/src/utils/collection';
import {type} from 'os';
import { DomSanitizer } from '@angular/platform-browser';
// import { Dropzone } from 'dropzone';
import { DropzoneComponent , DropzoneDirective,
    DropzoneConfigInterface } from 'ngx-dropzone-wrapper';


import { CompleterService } from '../typescripts/pro';



@Component({
    selector: 'app-book',
    templateUrl: './book.component.html',
    styleUrls: ['./book.component.css']
})
export class BookComponent implements OnInit, OnDestroy {
    @Input() socialIdUser: String;
    @Output() setAllUserAppFolder = new EventEmitter<String>();

    message: string = 'Hola Mundo!';
    sizeFile:any;
    @Output() messageEvent = new EventEmitter<string>();
    currentUser: any;
    allUserFile: any;
    allUserFolder: any;
    //socialIdUser: String;
    filterAllUserFolder: any;
    allUserAppFolder: any;
    allUserAppFile: any;
    mainFolder: any;
    books: any;
    filesToUpload: Array<File>;
    fileChooseName: string;
    httpOptions: any;
    isClickCreateFolder: boolean;
    inputCreateFolder: String;
    reader: FileReader;
    test: String;
    previewNode:any;
    previewTemplate:any;
    // config: DropzoneConfigInterface;
    //myDropzone: Dropzone;
    droptestt:any;
    allItems: any;


    searchStr: String;
    dataService: any;

    public type: string = 'component';

    public disabled: boolean = false;

    public config: DropzoneConfigInterface = {
        clickable: true,
        maxFiles: 1,
        autoReset: null,
        errorReset: null,
        cancelReset: null
    };

    @ViewChild(DropzoneComponent) componentRef?: DropzoneComponent;
    @ViewChild(DropzoneDirective) directiveRef?: DropzoneDirective;


    constructor(private completerService: CompleterService, private http: HttpClient, private router: Router, private route: ActivatedRoute, public sanitizer: DomSanitizer) {



        this.isClickCreateFolder = false;
        this.fileChooseName = 'None';
        console.log('this.fileChooseName' + this.fileChooseName);
        this.filesToUpload = [];
        this.test = '';
        this.sizeFile = 0;


    }
    copyLink(val) {

        let selBox = document.createElement('textarea');

        selBox.style.position = 'fixed';
        selBox.style.left = '0';
        selBox.style.top = '0';
        selBox.style.opacity = '0';
        selBox.value = 'https://localhost:3000/download/' + val;

        document.body.appendChild(selBox);
        selBox.focus();
        selBox.select();

        document.execCommand('copy');
        document.body.removeChild(selBox);
    }

    sendMessage() {
        this.messageEvent.emit('caca')
    }
    public toggleType(): void {
        this.type = (this.type === 'component') ? 'directive' : 'component';
    }

    public toggleDisabled(): void {
        this.disabled = !this.disabled;
    }

    public toggleAutoReset(): void {
        this.config.autoReset = this.config.autoReset ? null : 5000;
        this.config.errorReset = this.config.errorReset ? null : 5000;
        this.config.cancelReset = this.config.cancelReset ? null : 5000;
    }

    public toggleMultiUpload(): void {
        this.config.maxFiles = this.config.maxFiles ? 0 : 1;
    }

    public toggleClickAction(): void {
        this.config.clickable = !this.config.clickable;
    }

    public resetDropzoneUploads(): void {
        if (this.type === 'directive' && this.directiveRef) {
            this.directiveRef.reset();
        } else if (this.type === 'component' && this.componentRef && this.componentRef.directiveRef) {
            this.componentRef.directiveRef.reset();
        }
    }

    public onUploadError(args: any): void {
        console.log('onUploadError:', args);
    }
    filter(query: string) {
        var temp = (this.allUserAppFolder.concat(this.allUserAppFile));
        this.filterAllUserFolder = (query) ? temp.filter(p => (p.name.toLowerCase()).includes(query.toLowerCase())) : [];

    }
    public onUploadSuccess(args: any): void {
        this.filesToUpload = args;
        this.fileChooseName = args[0].name;

        // var reader = new FileReader();
        // reader.onload = function() {
        //     alert(reader.result);
        // };
        // reader.readAsText(args[0]);

        this.upload();
        this.resetDropzoneUploads();
        this.openFolder(this.mainFolder.path);

    }

    ngOnInit() {
        this.httpOptions = {
            headers: new HttpHeaders({
                'Authorization': localStorage.getItem('jwtToken'),
                'Access-Control-Allow-Origin' : '*',
                'Access-Control-Allow-Methods' : 'GET, POST, OPTIONS, PUT, PATCH, DELETE',
                'Access-Control-Allow-Headers' : 'Origin, X-Requested-With, Content-Type, Accept'
            }),
            pathFolder: ''
        };
        // this.httpOptions = {
        //     headers: new HttpHeaders({ 'Authorization': localStorage.getItem('jwtToken'), 'Access-Control-Allow-Origin' : '*'}),
        //     pathFolder: ''
        // };

        this.http.get('/api/getCurrentUser', this.httpOptions).subscribe(user => {
            this.currentUser  = user;
            this.openFolder('Home');
        }, err => {
            if (err.status === 401) {
                this.router.navigate(['login']);
            }
        });
    }

    deleteFile(fileToDelete) {
        this.http.post('/api/deleteFileMongo', fileToDelete).subscribe(file => {
            this.openFolder(this.mainFolder.path);
        });
    }

    deleteFolder(folderToDelete) {
        this.http.post('/api/deleteFolderMongo', folderToDelete).subscribe(folder => {
            this.openFolder(this.mainFolder.path);
        });
    }


    renameFolder(folderToRename) {
        folderToRename.path = this.mainFolder.path + '/' + folderToRename.name;

        this.http.post('/api/renameFolderMongo', folderToRename).subscribe(data => {
            console.log('data : ' + data);
        });
    }

    renameFile(fileToRename){
        this.http.post('/api/renameFileMongo', fileToRename).subscribe(data => {
            console.log('data : ' + data);
        });
    }
    saveURLFileMongo(fileToCreateURL){
        fileToCreateURL.url = '../../../public/' + fileToCreateURL._id.toString() + this.getStringExtention(fileToCreateURL);

        this.http.post('/api/saveURLFileMongo', fileToCreateURL).subscribe(data => {
            console.log('data : ' + data);
        });
    }

    getAllUserAppFiles() {
        this.http.post('/api/getFileAppList', {owner: this.currentUser.username.toString()}).subscribe(files => {
            if (files) {
                this.allUserAppFile = files;


                this.allItems = (this.allUserAppFolder.concat(this.allUserAppFile));
                this.dataService = this.completerService.local(this.allItems, 'name', 'path');


                for (let f of this.allItems){
                    console.log(f.name);
                    //f.fileTab = this.getfiles(f);
                }
                // return files;
            } else {
                this.allUserAppFile = [];
            }
        });
    }


    getfiles() {
        //var preview = document.querySelector('img');

        this.sizeFile = 0;
        var meee = this;

        this.http.post('/api/getFileList', {mainPath : this.mainFolder.path, owner: this.currentUser.username.toString()}).subscribe(files => {
            if (files) {


                this.allUserFile = files;
                for (let f of this.allUserFile) {

                    this.sizeFile += +f.taille;
                    if(f.type === ('image/jpeg') || f.type === ('image/png')){
                        f.data = f.url;
                        f.urlSafe = this.sanitizer.bypassSecurityTrustUrl(f.url);
                    }else{
                        f.data = f.url;
                        f.urlSafe = this.sanitizer.bypassSecurityTrustResourceUrl(f.url);
                    }
              }
          } else {
              this.allUserFile = [];
          }
          document.getElementById('openModalButton').click();
      });
  }

  getfolders() {
        this.http.post('/api/getFolderList', {mainPath : this.mainFolder.path, owner: this.currentUser.username.toString()}).subscribe(folders => {
          if (folders) {
              this.allUserFolder = folders;
          } else {
              this.allUserFolder = [];
          }
      });
  }
  getAllUserAppFolder(){
      this.message = '';
      this.sendMessage();
      this.http.post('/api/getFolderAppList', {owner: this.currentUser.username.toString()}).subscribe(folders => {
          if (folders) {
              this.allUserAppFolder = folders;

              this.setAllUserAppFolder.emit(this.currentUser.username.toString());

              this.getAllUserAppFiles();
          } else {
              this.allUserAppFolder = [];
          }
      });
  }

    moveFile(fileToMove, folderDest){
        fileToMove.path = folderDest.path;

        this.http.post('/api/moveFile', fileToMove).subscribe(data => {
            console.log('data : ' + data);
            this.getfiles();
            //this.openFolder(this.mainFolder.path)
            // this.getAllUserAppFolder();
            // this.getfiles();
        });
    }

    moveFolder(folderToMove, folderDest){
        var newPath = folderDest.path + '/' + folderToMove.parent.name;
        folderToMove.path = newPath;
        folderToMove.parent = folderDest.path;

        this.http.post('/api/moveFolder', folderToMove).subscribe(data => {
            console.log('data : ' + data);
            this.getfolders();
            //this.openFolder(this.mainFolder.path)
            // this.getAllUserAppFolder();
            // this.getfiles();
        });
    }

    backToParentFolder(){
        this.openFolder(this.mainFolder.parent);
    }


    openFolder(path: String) {

        if(this.searchStr !== undefined ? path === 'searchStr' : false){
            path = this.searchStr;

        }

        this.httpOptions.pathFolder = path;
        this.isClickCreateFolder = false;

        this.http.post('/api/getMainFolder', {path: path, owner: this.currentUser.username.toString()}).subscribe(folder => {
            if (folder) {
                this.mainFolder = folder;
                this.getfolders();
                this.getAllUserAppFolder();
                this.getfiles();

            } else {
                if (path === 'Home'){
                    this.http.post('api/createFolder', { name: 'Home', parent: '', path: 'Home', taille: 'taiile', idUser: this.currentUser._id.toString(), fileList: [], folderList: [], owner: this.currentUser.username.toString() }).subscribe(resp => {
                        this.mainFolder = resp;
                    }, err => {
                        console.log('err open Folder : ' + err);
                    });
                }
            }
        });
    }

    createBool() {
        this.isClickCreateFolder = true;
    }

    createFolder() {
        var newPath = this.mainFolder.path + '/' + this.inputCreateFolder;
        this.isClickCreateFolder = false;

        this.http.post('api/createFolder', { name: this.inputCreateFolder.toString(), parent: this.mainFolder.path, path: newPath.toString(), taille: 'taiile', idUser: this.currentUser._id.toString(), fileList: [], folderList: [], owner: this.currentUser.username.toString() }).subscribe(resp => {
            this.getfolders();
            this.getAllUserAppFolder();
        }, err => {
            console.log('err create Folder : ' + err);
        });
    }

    ngOnDestroy() {
        localStorage.removeItem('jwtToken');
        this.httpOptions = null;
        this.currentUser  = null;
    }

    upload() {
        var me = this;
        if(this.mainFolder !== undefined){
            this.http.post('api/uploadFileMongo', { name: this.fileChooseName.toString(), path: this.mainFolder.path.toString(), type: this.filesToUpload[0].type.toString(), taille: this.filesToUpload[0].size.toString(), idUser: this.currentUser._id.toString(), owner: this.currentUser.username.toString(), lastDate: Date.now().toString(), url: ''}).subscribe(resp => {
                me.saveURLFileMongo(resp);
                var mee = this;


                ////////
                me.makeFileRequest('https://localhost:3000/api/upload', [], this.filesToUpload, resp).then((result) => {
                    mee.getfiles();
                    mee.filesToUpload = null;
                    mee.fileChooseName = 'None';
                }, (error) => {
                    console.error(error);
                });
            }, err => {
                console.error(err);
            });
        }
    }

    fileChangeEvent(fileInput: any){
        this.filesToUpload = <Array<File>> fileInput.target.files;
        this.fileChooseName = this.filesToUpload[0].name;
    }


    makeFileRequest(url: string, params: Array<string>, files: Array<File>, monFile: any) {
        return new Promise((resolve, reject) => {
            var formData: any = new FormData();
            var xhr = new XMLHttpRequest();

            formData.append("public[]", files[0], monFile._id + this.getStringExtention(monFile));
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4) {
                    if (xhr.status == 200) {
                        resolve(JSON.parse(xhr.response));
                    } else {
                        reject(xhr.response);
                    }
                }
            };

            xhr.open("POST", url, true);
            xhr.send(formData);
        });
    }


    getStringExtention(monFile: any){
        return ( monFile.name.indexOf('.') > 0 ) ? '.' + monFile.name.split('.').pop().toLowerCase() : '';
    }
}


