import { Component, OnInit, OnDestroy } 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';

@Component({
  selector: 'app-book',
  templateUrl: './book.component.html',
  styleUrls: ['./book.component.css']
})
export class BookComponent implements OnInit, OnDestroy {
  currentUser: any;
  allUserFile: any;
  books: any;
  filesToUpload: Array<File>;
  fileChooseName: string;
  httpOptions: any;
  tokenFromLogin: any;
  constructor(private http: HttpClient, private router: Router, private route: ActivatedRoute) {

    this.fileChooseName = 'None';
    this.filesToUpload = [];
  }

  ngOnInit() {

    this.route.params.subscribe(params => {
      this.tokenFromLogin = params['tokenFromLogin'];

      this.httpOptions = {
        headers: new HttpHeaders({ 'Authorization': localStorage.getItem('jwtToken') })
      };

      this.http.get('/api/book', this.httpOptions).subscribe(user => {
        this.currentUser  = user;
        console.log('mothafuka cureent user : ' + JSON.stringify(this.currentUser));
      }, err => {
        if (err.status === 401) {
          this.router.navigate(['login']);
        }
      });

      this.http.get('/api/allUserFile', this.httpOptions).subscribe(files => {
        this.allUserFile  = files;
        console.log('mothafuka cureent user : ' + JSON.stringify(this.allUserFile));
      }, err => {
        if (err.status === 401) {
          this.router.navigate(['login']);
        }
      });
    });


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

    this.makeFileRequest('http://localhost:3000/api/upload', [], this.filesToUpload).then((result) => {
      // var source = 'http://localhost:3000/public/'+result[0].filename;
      console.log('current USer Filleeee ::: '+ JSON.stringify(this.currentUser));
      var fileUploadData = { uid: '222', name:result[0].filename.toString(), path: result[0].path.toString(), extention:this.filesToUpload[0].type.toString(), taille:this.filesToUpload[0].size.toString(), idUser: this.currentUser.id };
      var message = '';
      //console.log('mothafukaaaaaaaaaaa : ' + JSON.stringify(this.currentUser));
      //console.log('mothafukaaaaaaaaaaa : ' + this.currentUser._id);
      console.log('avaaaaanttttt : ' + this.currentUser.username.toString() + '     ----     ' + this.currentUser._id.toString());

      if(this.currentUser.username)
      this.http.post('api/uploadFileMongo', { name: result[0].filename.toString(), path: result[0].path.toString(), extention: this.filesToUpload[0].type.toString(), taille: this.filesToUpload[0].size.toString(), idUser: this.currentUser._id.toString(), owner: this.currentUser.username.toString() }).subscribe(resp => {
        console.log('ok db !!' + resp.toString());
      }, err => {
        console.log('errrrr : ' + err);
        message = err.error.msg;
      });
      console.log('apres');
      console.log('fileUploadData: ' + fileUploadData);
      console.log('fileUploadData.path: ' + fileUploadData.path);
      console.log('fileUploadData.name: ' + fileUploadData.name);
      console.log('fileUploadData.taille: ' + fileUploadData.taille);
      console.log('fileUploadData.extention: ' + fileUploadData.extention);

      console.log('result: ' + result[0].filename);


    }, (error) => {
      console.error(error);
    });
  }

  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>) {
    return new Promise((resolve, reject) => {
      var formData: any = new FormData();
      var xhr = new XMLHttpRequest();

      formData.append("public[]", files[0], files[0].name);
      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);
    });
  }

  logout() {
    this.httpOptions = null;
    localStorage.removeItem('jwtToken');
    this.router.navigate(['login']);
  }

}
