import {Component, EventEmitter, Input, OnDestroy, OnInit, Output, NgZone, OnChanges} from '@angular/core';
import {NzMessageService, NzNotificationService, UploadFile} from 'ng-zorro-antd';
import {HttpClient, HttpEvent, HttpEventType, HttpRequest} from '@angular/common/http';
import {environment} from '../../../environments/environment';

declare var Recorder;

@Component({
  selector: 'app-audio-recorder',
  templateUrl: './audio-recorder.component.html',
  styleUrls: ['./audio-recorder.component.scss']
})
export class AudioRecorderComponent implements OnInit, OnChanges, OnDestroy {
  _audioUrl: string;
  audio = new Audio();
  playIcon = 'play';
  isPlaying = false;
  isRecording = false;
  isUploading = false;
  type = Type.UPLOAD; // record | upload
  Type = Type;
  @Input()
  withRmBtn = false;

  uploadUrl;
  uploadData;

  @Input()
  needRemove = false;

  @Input()
  audioItem: any = null;

  @Input()
  _audioName: any = null;

  @Input()
  set audioUrl(url) {
    this._audioUrl = url;
    if (url) {
      this.httpHeadCall(this._audioUrl, flag => {
        if (flag) {
          this.audio.src = this._audioUrl;
        } else {
          this.audio.src = this._audioUrl.replace("_l.", ".");
        }
        this.audio.load();
      });
    }
    this.init();
  }

  get audioUrl() {
    return this._audioUrl;
  }

  @Output() audioUploaded = new EventEmitter();
  @Output() audioUploadFailure = new EventEmitter();
  @Output() audioRemoved = new EventEmitter();
  @Output() audioName = new EventEmitter();
  percent = 0;
  progress = 0;
  recorder: any;
  audioBlob: any;


  constructor( private nzMessageService: NzMessageService ) {
    this.uploadUrl = (<any> window).courseware.uploadUrl();
    this.uploadData = (<any> window).courseware.uploadData();

    window['air'].getUploadCallback = (url, data) => {
      this.uploadUrl = url;
      this.uploadData = data;
    };
  }

  httpHeadCall(requsetUrl: string, callback) {
    let xhr = new XMLHttpRequest();
    console.log("Status: Send Post Request to " + requsetUrl);
    try {
      xhr.onreadystatechange = () => {
        try {
          console.log('xhr.readyState: ', xhr.readyState);
          if (xhr.readyState == 4) {
            if ((xhr.status >= 200 && xhr.status < 400)) {
              callback(true);
            } else {
              callback(false);
            }
          }

        } catch (e) {
          console.log(e)
        }
      };
      xhr.open("HEAD", requsetUrl, true);
      xhr.send();
      xhr.timeout = 15000;
      xhr.onerror = (e) => {
        console.log("汪汪汪 posterror", e);
        callback(false);
      };
      xhr.ontimeout = (e) => {
        console.log("汪汪汪 ontimeout", e);
        callback(false);
      };
    } catch (e) {
      console.log("Send Get Request error: ", e)
    }
  }

  init() {
    this.playIcon = 'play';
    this.isPlaying = false;
    this.isRecording = false;
    this.isUploading = false;
    this.percent = 0;
    this.progress = 0;
    this.audioBlob = null;
  }
  ngOnChanges() {
    // if (!this.audioItem || !this.audioItem.type) {
    //   return;
    // }
    // this.beforeUpload(this.audioItem);
  }
  ngOnInit() {

    this.audio.onplay = () => {
      this.onPlay();
    };
    this.audio.onpause = () => {
      this.onPause();
    };
    this.audio.ontimeupdate = (event) => {
      this.onTimeUpdate(event);
    };
    this.audio.onended = (event) => {
      this.onEnded();
    };
  }

  ngOnDestroy() {
    this.audio.pause();
    this.isPlaying = false;
    this.audio.remove();
    // if (this.recorder.worker) {
    //   this.recorder.worker.terminate();
    // }
  }

  progressText(percent) {
    return ``;
  }

  onPlay() {
    console.log('play');
    this.playIcon = 'pause';
    this.isPlaying = true;
  }

  onPause() {
    console.log('pause');
    this.playIcon = 'play';
    this.isPlaying = false;
  }

  onEnded() {
    console.log('on end');
    this.playIcon = 'play';
    this.percent = 0;
    this.isPlaying = false;
  }

  onTimeUpdate(event) {
    this.percent = Math.floor((this.audio.currentTime / this.audio.duration) * 100);
  }

  onBtnPlay() {
    if (this.isRecording) {
      this.nzMessageService.warning('In Recording');
      return;
    }
    if (this.isPlaying) {
      this.audio.pause();
    } else {
      this.audio.play();
    }
  }

  // 开始录音
  onBtnRecord = () => {
  }

  // 切换模式
  onBtnSwitchType() {
  }
  onBtnClearAudio() {
    this.audioUrl = null;
    this.audioRemoved.emit();
  }

  onBtnDeleteAudio() {
    this.audioUrl = null;
    this.audioRemoved.emit();
  }

  handleChange(info: { type: string, file: UploadFile, event: any }): void {
    switch (info.type) {
      case 'start':
        this.isUploading = true;
        this.progress = 0;
        break;
      case 'success':
        this.isUploading = false;
        let url = info.file.response.url;
        url = url.substring(0, url.lastIndexOf(".")) + "_l.mp3";
        info.file.response.url = url;
        info.file.response.name = info.file.name;
        this.uploadSuccess(info.file.response);
        this.audioUploaded.emit(info.file.response);
        this.audioName.emit(info.file.name);
        break;
      case 'progress':
        this.progress = parseInt(info.event.percent, 10);
        break;
    }
  }
  checkSelectFile(file: any) {
    if (!file) {
      return;
    }
    const isAudio = ['audio/mp3', 'audio/wav', 'audio/ogg'].includes(file.type);
    if (!isAudio) {
      this.nzMessageService.error('You can only upload Audio file ( mp3 | wav |ogg)');
      return;
    }
    const delta =  25;
    const isOverSize = (file.size / 1024 / 1024) < delta;
    if (!isOverSize) {
      this.nzMessageService.error(`audio file  must smaller than ${delta}MB!`);
      return false;
    }
    return true;
  }
  beforeUpload = (file: File) => {

    this.audioUrl = null;
    if (!this.checkSelectFile(file)) {
      return false;
    }
    this.isUploading = true;
    this.progress = 0;
  }
  uploadSuccess = (url) => {
    this.nzMessageService.info('Upload Success');
    this.isUploading = false;
    this.audioUrl = url;
  }
  uploadFailure = (err, file) => {
    this.isUploading = false;
    if (err.name && err.name === 'cancel') {
      return;
    }
    console.log(err);
    this.nzMessageService.error('Upload Error ' + err.message);
    this.audioUploadFailure.emit(file);
  }
  doProgress = (p) => {
    if (p > 1) {
      p = 1;
    }
    if (p < 0) {
      p = 0;
    }
    // console.log(Math.floor(p * 100));
    this.progress =  Math.floor(p * 100);
  }

}

enum Type {
  RECORD = 1, UPLOAD
}
