import { Component, OnInit, ViewChild, Inject, Input, ElementRef, Output, EventEmitter } from '@angular/core';
import { CourseAPIService } from './course-api.service';
import { VgAPI } from 'ngx-videogular';
import { DashboardService } from '../../dashboard/dashboard.service';
import { Portal, TemplatePortalDirective } from '@angular/cdk/portal';
import {MatDialog,MAT_DIALOG_DATA,MatDialogRef} from '@angular/material/dialog';

@Component({
    selector: 'course-content',
    templateUrl: './course-content.component.html',
    styleUrls: ['./course-content.component.css']
})
export class CourseContentComponent implements OnInit {

    @Input() videoList: any;
    @Input() currentItem: any;
    @Input() selectedCourse: any;
    @Output() onCourseComplete: EventEmitter<any> = new EventEmitter();

    @ViewChild('scrollToMe') scrollToMe: ElementRef | any;
    @ViewChild(TemplatePortalDirective) templatePortal: Portal<any> | any;

    videoListData: any;
    curItemCourseCode: any;
    courseStatus: any;
    currentIndex = 0;

    constructor(private courseApiService: CourseAPIService, private dashboardService: DashboardService, public dialog: MatDialog) {
    }

    ngOnInit() {
        console.log('videoList=>', this.videoList);
        console.log('selectedCourse=>', this.selectedCourse);
        this.videoListData = this.videoList
        this.curItemCourseCode = this.selectedCourse.courseCode;
        this.courseStatus = this.selectedCourse.courseStatus ? this.selectedCourse.courseStatus.trim() : '';

        this.courseApiService.getCurrentItem().subscribe(currentItem => {
            this.currentItem = currentItem;
        });

        this.currentItem = this.videoListData[0];
        console.log('currentItem==>', this.currentItem)
        this.courseApiService.setVideoList(this.videoListData);
        this.courseApiService.setCurrentItem(this.currentItem);
        this.courseApiService.setCurCourseCode(this.curItemCourseCode);
    }

    onPlayerReady(vgObject: any) {
        this.courseApiService.onPlayerReady(vgObject);
    }

    selectVideo(item: any) {
        this.currentIndex = item.index;
        this.courseApiService.selectVideo(item);
        if (this.scrollToMe.nativeElement) {
            this.scrollToMe.nativeElement.scrollIntoView({ behavior: 'smooth' });
        }
    }
    //Changed By Vikas Lagad on 30-12-2019[To update status of playList]Start
    courseQuestionBtn(currentCourse: any) {
        try
        {
            console.log('courseQuestionBtn 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);
            }
        }
        catch(err)
        {
            console.log('Exception .....  ',err);
        };
        this.courseApiService.updatePlayStatus();
        //Changed By Vikas Lagad on 30-12-2019[To update status of playList]End
        if (this.courseStatus == 'C' || this.isAllContentSeen()) {
            this.openQuestionPage();
        }
        else {
            //alert('You have not  watched all videos still you want to proceed ?')
            const dialogRef = this.dialog.open(DialogOverviewExampleDialog, {});

            dialogRef.afterClosed().subscribe(result => {
                console.log('The dialog result after was closed==>', result);
                if (result) {
                    console.log('called')
                    this.openQuestionPage();
                }
            });
        }
    }

    isAllContentSeen() {
        var isAllContentSaw = true;
        this.videoListData.map((videoItem: any) => {
            console.log('Current Time :: '+videoItem.time.current +' Total Time :: '+ videoItem.time.total);
            if (videoItem.time && videoItem.time.current >= videoItem.time.total) {
                console.log('isAllContentSeen >> videoItem : ', videoItem);
            }
            else {
                isAllContentSaw = false;
            }
        });
        return isAllContentSaw;
    }

    openQuestionPage() {
        this.courseApiService.api.pause();
        var linkInfo: any = {};
        linkInfo["TargetObject"] = 'course-question';
        linkInfo["LinkForm"] = 'LINK';
        linkInfo['callBack'] = this.callBackFunc.bind(this);
        var compData = this.selectedCourse;
        this.dashboardService.invokeAngCompLink(linkInfo, '', '', this.templatePortal, compData);
    }

    onClickOfPrevious() {
        this.currentIndex--;
        this.currentItem = this.videoListData[this.currentIndex];

        this.courseApiService.selectVideo(this.currentItem);
    }

    onClickOfNext() {
        this.currentIndex++;
        this.currentItem = this.videoListData[this.currentIndex];
        this.courseApiService.onLoadPlay = true;
        this.courseApiService.selectVideo(this.currentItem);
    }

    logDocUsage(docUsageData: any) {
        this.courseApiService.logDocUsage(docUsageData).subscribe(
            resp => {
                console.log('Response', resp);
            }
        );
    }

    callBackFunc() {
        console.log('Call back in Course Content Component');
        this.onCourseComplete.emit();
    }
}

// TODO: Create a message component to display a Message w.r.t. MSG_NO refer from Messages Table
//Previous Message  : <p>You have not watched all video still you want to proceed?</p>
//New Message       : <p>You have not watched complete video do you still want to proceed</p>
//New Message       : <p>You have not completed watching the videos do you still want to proceed</p>
@Component({
    selector: 'dialog-overview-example-dialog',
    template: `
                <div  style="width: 36px;vertical-align: top;margin: auto;display: block;padding: 0 0 1em 0;">
                <img src="{{imgPath}}">
                </div>
                <div  style="position: relative;font-size: 1.2em;max-width: 300px;min-width: 250px;">
                <p>You have not completed watching the videos. Do you still want to proceed?</p>
                </div>
                <div mat-dialog-actions style="float: right;">
                <button mat-raised-button (click)="onNoClick()">Cancel</button>
                <button mat-raised-button [mat-dialog-close]="'onYes'" cdkFocusInitial>Ok</button>
                </div>
    `,
})
export class DialogOverviewExampleDialog implements OnInit {
    imgPath: any;
    constructor(
        public dialogRef: MatDialogRef<DialogOverviewExampleDialog>,
        @Inject(MAT_DIALOG_DATA) public data: '',
        private courseApiService: CourseAPIService) { }

    ngOnInit() {
        this.imgPath =  this.courseApiService.assetImageUrl + "/svg/Error_Alert.svg"
    }

    onNoClick(): void {
        this.dialogRef.close();
    }

}
