import {
  AfterViewInit,
  ApplicationRef,
  ChangeDetectorRef,
  Component,
  ElementRef,
  Input,
  OnDestroy,
  OnInit,
  ViewChild
} from '@angular/core';

@Component({
  selector: 'app-play',
  templateUrl: './play.component.html',
  styleUrls: ['./play.component.scss']
  // encapsulation: ViewEncapsulation.None,
})
export class PlayComponent implements AfterViewInit, OnInit, OnDestroy {
  @Input() data;
  @Input() sid;
  @ViewChild('videoNode')
  videoNodeRef: ElementRef;
  @ViewChild('videoProgress')
  videoProgressRef: ElementRef;
  player: any;
  progress = 0;
  currentTime = 0;
  duration = 0;
  isPlaying = false;
  hasVideo = false;
  touchSeeking = false;
  initCover = false;

  KEY = 'hw_002';
  playBtnImg = '';
  // aaa;


  constructor(private appRef: ApplicationRef,
              public changeDetectorRef: ChangeDetectorRef) {
  }

  ngOnInit() {
    // console.log(this.data.contentObj)
    // this.hasVideo = !!this.data.contentObj.video_url && typeof this.data.contentObj.video_url === 'string';

    this.data = {};
    this.data.contentObj = {};

    const getData = (<any> window).courseware.getData;
    getData((data) => {

      if (data && typeof data == 'object') {
        this.data = data;
      } else {
        this.data = {};
      }

      console.log('data:' , this.data);
      if (!this.data.contentObj) {
        this.data.contentObj = {};
      }

      this.initDefaultData();

      console.log('this.data.contentObj.video_url: ', this.data.contentObj.video_url);


      this.hasVideo = !!this.data.contentObj.video_url && typeof this.data.contentObj.video_url === 'string';

      console.log('hasVideo: ', this.hasVideo);
      this.playBtnImg = 'assets/play/btn-play.png';




      window['air'].hideAirClassLoading(this.KEY, this.data);



      this.refresh();

    }, this.KEY);


    // this.aaa = {a: 1};
    // setInterval(() => {
    //   this.aaa.a ++;
    // }, 1000);

    setInterval(() => {
      this.refresh();
    }, 1000);
  }

  initDefaultData() {
    if (!this.data.contentObj.video_url) {
      this.data.contentObj.video_url = 'assets/default/demo.mp4';
    }
  }

  playVideo() {
    // console.log(333333)
    if (!this.videoNodeRef) {
      return;
    }

    if (!this.player) {
      this.ngAfterViewInit();
    }

    if (!this.player) {
      console.log(' player not exist');
      return;
    }
    this.initCover = false;
    if (this.player.paused) {
      const playPromise = this.player.play();

      if (playPromise !== undefined) {
        playPromise.then(_ => {
          // Automatic playback started!
          // Show playing UI.
          console.log('play', _);
        })
        .catch(error => {
          // Auto-play was prevented
          // Show paused UI.
          console.log('error', error);
        });
      }

      this.playBtnImg = 'assets/play/btn-play.png';

    } else {
      this.player.pause();
    }


    this.refresh();
  }

  ngAfterViewInit() {
    console.log(' in ngAfterViewInit');
    if (!this.videoNodeRef) {
      return;
    }
    this.player = this.videoNodeRef.nativeElement;
    this.player.ontimeupdate = (event) => {
      this.onTimeUpdate(event);
    };
    this.player.onloadedmetadata = () => {
      this.currentTime = 0;
      this.duration = this.player.duration;

    };
    this.player.onseeking = () => {
      this.player.pause();
    };
    this.player.onseeked = () => {
      this.player.play();
      this.touchSeeking = false;
    };
    this.player.onplay = () => {
      this.isPlaying = true;
    };
    this.player.onpause = () => {
      this.isPlaying = false;
    };
    this.player.addEventListener("ended", () => {
      this.playBtnImg = 'assets/play/btn-replay.png';

      this.refresh();
    })
    setTimeout(() => {
      this.initCover = this.data.contentObj.video_cover_url;
    });
  }

  ngOnDestroy() {
  }

  onTimeUpdate(event) {
    const player = event.target;
    this.currentTime = player.currentTime;
    this.progress = Math.floor((player.currentTime / player.duration) * 100);

    this.duration = this.player.duration;

  }

  onBtnQuickSeek(delta: number) {
    this.player.currentTime += delta;
  }

  onProgressMouseDown(event) {
    this.player.pause();
    this.touchSeeking = true;
  }

  onProgressMouseMove(event) {
    if (this.touchSeeking) {
      const {target, offsetX} = event;
      this.progress = Math.floor(offsetX / target.clientWidth * 100);
    }
  }

  onProgressMouseUp(event) {
    const {target, offsetX} = event;
    this.player.currentTime = this.player.duration * offsetX / target.clientWidth;
  }


  refresh() {
    setTimeout(() => {
      this.appRef.tick();
    }, 1);
  }
}
