import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { ToastrService } from 'ngx-toastr';
import {UploaderService} from './uploader.service'; 
// import {ZipService} from  './ZipService/zip.service';
import * as fileobj from 'src/assets/zip/demo2.js';
import {Observable, Subscription} from 'rxjs/Rx';

declare var $: any; 
 

@Component({
  selector: 'app-uploader',
  templateUrl: './uploader.component.html',
  styleUrls: ['./uploader.component.css'],
 //  providers:[ZipService]
})
export class UploaderComponent implements OnInit {
  private sub: any;
  trankey: any;
  userid: any;   
  error_message = '';
  lotstatus = '';
  valid: boolean;
  msgbox = '';
  msgbo12 = 'red';
  msgalert = 'dimgray';
  bar = '0%';
  percent = '';
  jobtitle: any;
  jobno: any;
  lottitle: any;
  project_subtitle: any;
  stagename_alias: any;
  public passkey: any;
  TotalParts_ = 0;
  PartCount_ = 0;
  msgfile = '';
  msgscrl = '';
  tranid: any;
  btncrl = 0;
  file:any;
  key:any;
  constructor(private route: ActivatedRoute, private toastr: ToastrService, private uploaderService: UploaderService,
   // private zipService: ZipService
    ) { }

  ngOnInit(): void {
console.log(this.route.snapshot.queryParams);
this.trankey = this.route.snapshot.queryParams.L;
this.userid = +this.route.snapshot.queryParams.U;
this.tranid = +this.route.snapshot.queryParams.T;
this.key = this.route.snapshot.queryParams.K; 
   this.uploaderService.validateJob(this.trankey).subscribe(res => {
    if (res !== null && res !== undefined) {
      if (res[0].lotstatus === 'P' || res[0].lotstatus=== 'R' ) {
        this.lotstatus = 'WIP';
        this.valid = true;
        this.getJobDetails();
      } else if (res[0].lotstatus === 'C')  {
        this.valid = false;
        this.getJobDetails();
				this.lotstatus = 'Completed';
				this.msgbox = 'Already Completed the Job';
      } else {
        this.valid = false;
				this.msgbox = 'Job not Avaliable';
      }
    }
   }, err => {
     console.log(err);
    this.valid = false;
    this.msgbox = 'Link is not valid';
     this.toastr.error('Link is not valid');
   });

  }

  getJobDetails() {
    this.uploaderService.getJobDetails(this.trankey).subscribe(res => {
      console.log(res);
      if (res !== null && res !== undefined) {
        this.jobtitle = res[0].jobtitle;
        this.jobno = res[0].jobno;
        this.lottitle = res[0].lottitle;
        this.project_subtitle = res[0].project_subtitle;
        this.stagename_alias = res[0].stagename_alias;
        this.passkey = this.trankey;
      }
    }, err => {      
       this.toastr.error('Error in Get Job details');
     });
  }
  fileChanged(event) {
    this.file = event.target.files[0];   
    this.btncrl = 1;
      this.msgalert = 'dimgray';
  }

  uploadfile() {
    let files = $('#file-input').get(0).files;
   // let files =this.file;
       let flist:any;
    if (files.length > 0) {
      debugger;
           this.uploadFiles( $('#file-input').get(0).files);
  }else {
      this.toastr.error('Kindly select the file to upload and then proceed');
    }      
  }

 
  
   /* myTimer() {
    if ($('#file-input')[0].files.length > 0) {
      debugger;
                  this.btncrl = 1;
                  this.msgalert = 'dimgray';
       
    }
       /*  if ($('#file-input')[0].files.length > 0) {
          debugger;
          this.btncrl = 0;
          this.msgalert = 'red';
         let filePassList_ = fileobj.filePassList;
            if (filePassList_.length > 0) {
               console.log(filePassList_);
               this.btncrl = 0;
               this.msgalert = 'red';
               //this.trankey = this.route.snapshot.queryParams.L;
               for (var i = 0; i < filePassList_.length; i++) {
                    var password = filePassList_[i][3].trim();
                    if (this.passkey.trim() == password) {
                      this.btncrl = 1;
                      this.msgalert = 'dimgray';
                    }
                } 
            }
            else {
              this.btncrl = 0;
              this.msgalert = 'red';
            }
        }
    
    }   */

  uploadFiles(targetFiles)
  {
    debugger;
    for (let i = 0; i < targetFiles.length; i++) {
      this.UploadFileTarget(targetFiles[i]);
  }
  }

  UploadFileTarget(TargetFile) {
    debugger;
    let FileChunk = [];    
    let file = TargetFile;
    let MaxFileSizeMB = 0.5;
    let BufferChunkSize = MaxFileSizeMB * (1024 * 1024);
    let ReadBuffer_Size = 1024;
    let FileStreamPos = 0;
    let EndPos = BufferChunkSize;
    let Size = file.size;

    while (FileStreamPos < Size) {
        FileChunk.push(file.slice(FileStreamPos, EndPos));
        FileStreamPos = EndPos; // jump by the amount read
        EndPos = FileStreamPos + BufferChunkSize; // set next chunk length
    }
    // get total number of "files" we will be sending

    let TotalParts = FileChunk.length;
    this.TotalParts_ = this.TotalParts_ + TotalParts
    let PartCount = 0;
    // loop through, pulling the first item from the array each time and sending it
    let chunk: any;
    while (chunk = FileChunk.shift()) {
        PartCount++;
        let FilePartName = file.name + '.part_' + PartCount + '.' + TotalParts;
        this.UploadFileChunk(chunk, FilePartName);
    }
  }

  UploadFileChunk(chunk, FileName) {
    debugger;
    let FD = new FormData();
    let TOC = '0';
    this.msgscrl = '0';
    FD.append('file', chunk, FileName + '~' + this.trankey.trim()+'~'+this.tranid+'~'+this.userid+'~'+this.key);
    let subscription: Subscription;
  this.uploaderService.UploadFile(FD).subscribe(res =>{
      this.PartCount_++;
      this.msgfile = res[0];
      let percentValue = ((this.PartCount_ / this.TotalParts_) * 100);
     // sCount = percentValue;
      this.bar = percentValue + '%';
      this.percent = Math.round(percentValue) + '%';
      if (percentValue >= 90.00) {
          this.percent = 'Please Wait. Validating the File';
      }
    }, complete => {
      if(complete.statusText == 'OK'){
     // if (this.PartCount_ === this.TotalParts_) {
        this.msgscrl = '1';
        console.log(complete.error);
       // var n == this.msgfile.includes('Successfully');
        if (complete.error.text.includes('Successfully') === true) {
          this.toastr.success(complete.error.text);            
            this.msgbox = this.msgfile;
            this.msgbo12 = 'green';
            this.valid = false;
            this.lotstatus = 'Completed';
            this.msgbox =complete.error.text;

        }  else {
          this.toastr.error(complete.error.text);
            this.msgbox = complete.error.text;
            this.msgbo12 = 'red';
        }

        this.percent = 'Completed..';
       $('#file-input')[0].value = ''; 
        let percentValue = 0;
        this.bar = percentValue + '%';
        this.percent = percentValue + '%';
     }
    });
 
  }
}
