import { Component, OnInit, NgZone, OnDestroy, Input, Output, EventEmitter } from '@angular/core';
import { CourseAPIService } from './course-contents/course-api.service';
//import { courseLibrarySource } from './course-contents/bb-video-source';
// import { Subscription } from 'rxjs/Subscription';
import { Subscription } from 'rxjs';

@Component({
    selector: 'course-library',
    templateUrl: './course-library.component.html',
    styleUrls: ['./course-library.component.css']
})
export class CourseLibraryComponent implements OnInit, OnDestroy {
    @Input('data') courseLibData: any;
    @Output() onRefreshCourseData: EventEmitter<any> = new EventEmitter();

    videoData: any;
    videoContData: any;
    videoOpenData: any;
    trendVideoData: any;
    cardSelect: boolean = false;
    videoList: any;
    selectedCourse: any;
    displayOLength = 6;
	displayCLength = 6;
	displayTLength = 6;
    showAllOpenData: boolean = true;
    showAllContinueData: boolean = true;
    showAllTrending: boolean = true;
    videoBacktime: any;

    totalVideoPerWatched: any;
    previewImageErrorCount = 0;
    ASSET_IMG_URL = "dashboard/assets/images";
    isDummyImg: any;
    curentItemCourseCode: any;
    calcTotalVideTime = 0;
    currentIndex = 0;
    subscription: Subscription | any;
    courseSubs: Subscription | any;
    trendingSubs: Subscription | any;
    hostUrl: any;
  
    constructor(private courseApiService: CourseAPIService, public zone: NgZone) { }

    ngOnInit() {
        this.hostUrl = this.courseApiService.hosturl;
        this.getCourseData();
    }

    onSelectCard(data: any) {
        console.log('datass==>', data);
        this.selectedCourse = data
        console.log('selectedCourse ==>', this.selectedCourse);

        this.curentItemCourseCode = this.selectedCourse.courseCode;
        console.log('curentItemCourseCode==>', this.curentItemCourseCode);
        this.videoList = this.selectedCourse.courseContents;

        console.log('this.videoList==>', this.videoList);

        this.cardSelect = true; //TO Move from courseLibrary to course-content
        this.courseApiService.onLoadPlay = false;
        this.updateStatusBar(data, true);
    }

    brokenImage(event: any) {
        event.target.src = this.ASSET_IMG_URL + '/svg/broken-image.svg';
    }

    backPageBtn(currentCourse: any) {
        console.log('onClicback==>', currentCourse);

        var videoListData = currentCourse.courseContents;

        if (videoListData && videoListData.length > 0) {
            var currentItem = videoListData[this.currentIndex];
            console.log('currentItem in courseLibrary==>', currentItem);
            this.courseApiService.selectVideo(currentItem);
        }
        this.updateStatusBar( currentCourse, true );
       // this.cardSelect = false;
       this.getCourseData();
        //this.getTrendingCourseData(true);
    }

    updateStatusBar(data: any, isUpdate: any) {
        console.log('updateStatusBar ==>', data, 'isUpdate==>',isUpdate);

        var videoListData = data.courseContents;
        console.log('videoListData at statusBar fun==>', videoListData)
        var videoCurrentTime = 0;
        var videoTotalTIme = 0;
        if (videoListData && videoListData.length > 0) {
            for (var i = 0; i < videoListData.length; i++) {
                var currenTime = videoListData[i].time['current'];
                console.log('currenTime==>', currenTime);

                videoCurrentTime = videoCurrentTime + parseInt(currenTime);

                var totalTime = videoListData[i].time['total'];
                console.log('totalTime==>', totalTime);

                //videoTotalTIme = this.calcTotalVideTime;
                videoTotalTIme = videoTotalTIme + totalTime;

            }
            console.log('totalCurrentTIme[', videoCurrentTime, ']videoTotalTIme[', videoTotalTIme, ']');
            var valuInPercent = ((videoCurrentTime / videoTotalTIme) * 100).toFixed();
            console.log('valuInPercent at courseLib==>', valuInPercent);
            data['fullVideoAccesPos'] = valuInPercent;
        }

        var courseStatus = data['courseStatus'];
        console.log('courseStatus ::::',courseStatus);
       /* if(isUpdate && ( (courseStatus === 'O') || (courseStatus === 'T' ) )) */
       if(isUpdate &&  (courseStatus === 'O')  ) 
       {
            var url = '/course/'+this.curentItemCourseCode
            data['courseStatus'] = 'P';
            var courseData = {
                    'courseStatus' : 'P',
                    'courseRating' : ''        
            };
            
            console.log('courseStatus inside ::::',courseStatus);
          /*  if(courseStatus === 'T')
            {
                this.videoContData.push(data);
                console.log('trendVideoIndex data courseCode==>',data.courseCode);
                console.log('trendVideoIndex==>',this.trendVideoData.indexOf(data));
                this.trendVideoData.splice( this.trendVideoData.indexOf(data),1);
            } */
            this.courseApiService.saveCourseAttData(url, courseData).subscribe(
                  (res: any) => {
                      console.log('saveCourseAttAData',res)
                  }
            );
        } 
        
        /*
        var questionList = data.courseQuestions;
        console.log('questionList at statusBar fun==>', questionList)
        var quesResult = questionList.filter(question => {
            if (question.testData !== 'NA') {
                return {
                    "quesSet": question.quesSet,
                    "seqNo": question.seqNo,
                    "testData": question.testData
                };
            }
        });
        console.log('quesResult at statusBar fun==>', quesResult)
        var isAllQuesAttempted = quesResult.length == questionList.length;
        //TO add and update courseStatus and courseRating for courseContentAtt from dataBase Start
       /* var url = '/course/' + this.curentItemCourseCode
        var courseStatus = data['fullVideoAccesPos'] >= 100 && isAllQuesAttempted ? 'C' : 'P';
        data['courseStatus'] = courseStatus;
        if (isUpdate) {
            var courseData = {
                'courseStatus': courseStatus,
                'courseRating': ''
            };

            if (this.courseSubs) {
                this.courseSubs.unsubscribe();
            }
            this.courseSubs = this.courseApiService.saveCourseAttData(url, courseData).subscribe(
                res => {
                    console.log('saveCourseAttAData', res)
                }
            );
        }*/
        //TO add and update courseStatus and courseRating for courseContentAtt from dataBase End
    }

    /* getCourseData(isRefresh) {
         this.cardSelect = false;
         this.zone.run(() => {
             console.log('view refreshed');
         });
 
         if (this.subscription) {
             this.subscription.unsubscribe();
         }
          this.subscription = this.courseApiService.loadCourseLibraryData(isRefresh).subscribe(
              (courseLibraryData: courseLibrarySource[]) => {
                  this.videoData = courseLibraryData['courses'];
                  console.log('courseLibraryData==>', this.videoData);
                  this.videoOpenData = Object.assign([], this.videoData).filter(
                      vidItem => vidItem.courseStatus == 'O');
                  console.log('courseLibraryData= videoOpenData =>', this.videoOpenData);
                  this.videoContData = Object.assign([], this.videoData).filter(
                      vidItem => vidItem.courseStatus == 'P');
                  console.log('courseLibraryData= videoContData =>', this.videoContData);
  
                  this.videoContData = this.videoContData.map(updateCourse => {
                      if (updateCourse) {
                          updateCourse.courseContents = updateCourse.courseContents.map(
                              videoItem => {
                                  console.log('videoItem in videoList==>', videoItem);
                                  var prevTime = videoItem.time;
                                  var newTime = { 'current': 0, 'left': 0, 'total': 0 }
                                  var accessPos = videoItem.accessPos;
                                  if (prevTime) {
                                      var totalTime = parseInt(prevTime.total);
                                      var currentTime = totalTime * (accessPos / 100);
                                      var leftTime = totalTime - currentTime;
                                      newTime.total = totalTime;
                                      newTime.current = currentTime;
                                      newTime.left = leftTime;
                                  }
                                  console.log('prevTime in videoItem==>', prevTime, newTime);
                                  videoItem.time = newTime;
                                  return videoItem;
                              });
                          this.updateStatusBar(updateCourse, false);
                      }
                      return updateCourse;
                  });
              }
          ); 
         
     }  */

    getCourseData() {
       this.cardSelect = false;
        this.zone.run(() => {
            console.log('view refreshed');
        });
        //To fetch course-library videos data Start
        console.log('courseLibData===>',this.courseLibData);
        this.videoData = this.courseLibData.data['courses'];
        console.log('courseLibraryData==>', this.videoData);
        this.videoOpenData = Object.assign([], this.videoData).filter(
            (vidItem: any) => vidItem.courseStatus == 'O');
        console.log('courseLibraryData= videoOpenData =>', this.videoOpenData);
        this.videoContData = Object.assign([], this.videoData).filter(
            (vidItem: any) => vidItem.courseStatus == 'P');
        console.log('courseLibraryData= videoContData =>', this.videoContData);

        this.videoContData = this.videoContData.map((updateCourse: any) => {
            if (updateCourse) {
                updateCourse.courseContents = updateCourse.courseContents.map(
                    (videoItem: any) => {
                        console.log('videoItem in videoList==>', videoItem);
                        var prevTime = videoItem.time;
                        var newTime = { 'current': 0, 'left': 0, 'total': 0 }
                        var accessPos = videoItem.accessPos;
                        if (prevTime) {
                            var totalTime = parseInt(prevTime.total);
                            var currentTime = totalTime * (accessPos / 100);
                            var leftTime = totalTime - currentTime;
                            newTime.total = totalTime;
                            newTime.current = currentTime;
                            newTime.left = leftTime;
                        }
                        console.log('prevTime in videoItem==>', prevTime, newTime);
                        videoItem.time = newTime;
                        return videoItem;
                    });
                this.updateStatusBar(updateCourse, false);
            }
            return updateCourse;
        });
        //To fetch course-library videos data End

        //To fetch trending videos data Start
        this.getTrenData();
        //To fetch trending videos data End
    }

    getTrenData(){
        this.trendVideoData = this.courseLibData.data['trending-courses'];
        console.log('trendVideoData==>', this.trendVideoData);
    }

    //Added to get courseTrend data Start
    /* getTrendingCourseData(isRefresh) {
         this.cardSelect = false;
         if (this.trendingSubs) {
             this.trendingSubs.unsubscribe();
         }
         this.trendingSubs = this.courseApiService.loadCourseLibTrendingData(isRefresh).subscribe(
             (courseLibraryTrendingData: courseLibrarySource[]) => {
                 console.log("res for getTrending data==>", courseLibraryTrendingData);
                 this.trendVideoData = courseLibraryTrendingData['courses'];
             }
         )
     }
     //Added to get courseTrend data End
     */
    ngOnDestroy() {
        if (this.subscription) {
            this.subscription.unsubscribe();
        }
    }
    
    setShowState(option: any, state: any, count: any)
    {
        switch( option )
        {
            case 'O' : this.showAllOpenData = state; this.displayOLength = count; break;
            case 'C' : this.showAllContinueData = state; this.displayCLength = count; break;
        }
        
    }
    
    getShowState(option: any)
    {
        var state ;
        switch( option )
        {
            case 'O' : state = this.showAllOpenData; break;
            case 'C' : state = this.showAllContinueData; break;
        }
        return state;
    }

	getDisplayLen(option: any)
    {
        var len = 6 ;
        switch( option )
        {
            case 'O' : len = this.displayOLength; break;
            case 'C' : len = this.displayCLength; break;
        }
        return len;
    }
}
