import { Injectable } from '@angular/core';

import { HttpClient, HttpHeaders,HttpResponse} from '@angular/common/http';
import { Observable, BehaviorSubject } from 'rxjs';
import { map } from 'rxjs/operators';
import { catchError } from 'rxjs/operators';
import { DatePipe } from '@angular/common';
import { VgAPI } from 'ngx-videogular';
import { courseLibrarySource } from './bb-video-source';
import { getHostURL, getAssetImgUrl } from '../../shared/hostUrl';
import { DashboardService } from '../../dashboard/dashboard.service';
// import { Subscription } from 'rxjs/Subscription';
import { Subscription } from 'rxjs';
// import 'rxjs/Rx';
import { throwError } from 'rxjs';

@Injectable()
export class CourseAPIService {

    //SERVICE_URL = '/ibase/E12BROWSER/dashboard/assets/course-content/bb-video-source.json';
    API_URL = '/ibase/rest/api'; // URL to web service
    CERT_URL = '/ibase/rest/E12ExtService'; // URL to E12ExtService
    SERVICE_URL = '';
    hosturl;
    assetImageUrl;

    videoList: any;
    currentItem: any;
    onLoadPlay: boolean = false;
    currentPlayedVideoTime: any;
    courseCodeData: any;


    currentVidTime: any;
    api: VgAPI | any;
    media: any;
    onPause: any;
    private currentItemObs = new BehaviorSubject<any>({});

    fetchCourseLibData = new BehaviorSubject<any>({});
    fetchCourseLibTrendingData = new BehaviorSubject<any>({});
    courseContentSubs: Subscription | any;

    constructor(private http: HttpClient, private datePipe: DatePipe, private dashboardService: DashboardService, ) {
        this.hosturl = getHostURL();
        this.SERVICE_URL = this.hosturl + this.API_URL;
        this.assetImageUrl = getAssetImgUrl();
    }

    setCurrentItem(currentItem: any) {
        this.currentItem = currentItem;
    }
    setVideoList(videoList: any) {
        this.videoList = videoList;
    }
    getCurrentItem(): Observable<any> {
        return this.currentItemObs.asObservable();
    }

    setCurCourseCode(curCourseCode: any) {
        this.courseCodeData = curCourseCode;
    }

 /* loadCourseLibraryData(isRefresh): Observable<courseLibrarySource[]> {
        var courseConfig = localStorage.getItem('courseLibraryDataStorage');
        var reportJson;
        if (courseConfig && courseConfig != null && courseConfig.trim() && !isRefresh) {
            console.log('inside if when courseConfig is present==>', courseConfig);
            reportJson = JSON.parse(courseConfig);
            this.fetchCourseLibData = new BehaviorSubject<any>(reportJson);
        }
        else {
            console.log('inside else when courseConfig not present==>')
            let url = this.SERVICE_URL + "/course/all";
            let headers = new Headers({ 'Content-Type': 'application/json' });
            let options = new RequestOptions({ headers: headers });
            this.http.get(url, options)
                .map((res) => this.extractData(res))
                .subscribe(
                    response => {
                        console.log("response in courseLib service", response);
                        if (response) {
                            var courseLibData = response;
                            localStorage.setItem('courseLibraryDataStorage', JSON.stringify(courseLibData));
                            console.log('----localStorage data in course-library', courseLibData);
                            this.fetchCourseLibData.next(courseLibData);
                        }
                        else {
                            this.fetchCourseLibData.next('');
                        }
                    }
                );
        }
        return this.fetchCourseLibData;
   }  */

    //Added to get courseTrend data Start
   /* loadCourseLibTrendingData(isRefresh): Observable<courseLibrarySource[]> {
        var courseConfig = localStorage.getItem('courseLibraryTrendingDataStorage');
        var reportJson;
        if (courseConfig && courseConfig != null && courseConfig.trim() && !isRefresh) {
            console.log('inside  loadCourseLibTrendingData if when courseConfig is present==>', courseConfig);
            reportJson = JSON.parse(courseConfig);
            this.fetchCourseLibTrendingData = new BehaviorSubject<any>(reportJson);
        }
        else {
            console.log('inside else loadCourseLibTrendingData when courseConfig not present==>')
            let url = this.SERVICE_URL + "/course/trendings";
            let headers = new Headers({ 'Content-Type': 'application/json' });
            let options = new RequestOptions({ headers: headers });
            this.http.get(url, options)
                .map((res) => this.extractData(res))
                .subscribe(
                    response => {
                        console.log("response loadCourseLibTrendingData in courseLib service", response);
                        if (response) {
                            var courseLibTrendingData = response;
                            localStorage.setItem('courseLibraryTrendingDataStorage', JSON.stringify(courseLibTrendingData));
                            console.log('----localStorage trending data in course-library', courseLibTrendingData);
                            this.fetchCourseLibTrendingData.next(courseLibTrendingData);
                        }
                        else {
                            this.fetchCourseLibTrendingData.next('');
                        }
                    }
                );
        }
        return this.fetchCourseLibTrendingData;
    }*/
   //Added to get courseTrend data End
   
    private extractData(res: Response) {
        let body: any = res.json();
        console.log('extractData[' + JSON.stringify(body) + ']');
        return body || {};
    }

    private handleError(error: Response | any) {
        // In a real world app, we might use a remote logging infrastructure
        let errMsg: string;
        if (error instanceof Response) {
            const body: any = error.json() || '';
            //const err = body.error || JSON.stringify(body); commented by Vikas Lagad on 07-05-2020
            const err = body['error'] || JSON.stringify(body);
            errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
        } else {
            errMsg = error.message ? error.message : error.toString();
        }
        console.error('Service handleError:' + errMsg);
        // return Observable.throw(errMsg);
        return throwError(errMsg);
    }

    onPlayerReady(vgObject: any) {
        this.api = vgObject.vgApi;
        this.media = vgObject.vgMedia;
        console.log('api on service-->', this.api, this.media)
        this.api.getDefaultMedia().subscriptions.loadedMetadata.subscribe(this.playVideo.bind(this));
    }

    private playVideo() {
        var time = this.media.time;
        var currTime = this.currentItem.time;
        console.log('time===>', time)
        if( isNaN(currTime.current) )
        {
            this.currentVidTime = time;
        }
        else
        {
            this.currentVidTime = currTime;
        }
        console.log('currentVidTime==>', this.currentVidTime)

        if (this.currentVidTime) {
            this.media.time = this.currentVidTime;
            this.api.seekTime(this.getMiliSecond(this.currentVidTime.current));
        }
        else {
            this.currentItem.time = time;
        }
        if (this.onLoadPlay) {
            this.media.play();
        }

        console.log('playVideo time==>', time);
        console.log('playVideo previous time==>', this.currentVidTime);

        //TO Play video from start on click when it is full played.
        if (time['total'] === this.currentVidTime['current']) {
            console.log('logic is right');
            console.log('api==>', this.api, 'media==>', this.media);
            this.media['vgMedia'].currentTime = 0;
            this.media.play();
        }

    }

    selectVideo(item: any) {

        this.onLoadPlay = true;
        console.log('on click of slected video in apiService');

        var time = this.media.time;
        console.log('onClickPlaylistItem time==>', time);
        this.currentItem.time = time;
        console.log('current item time', this.currentItem.time);
        this.updatePlayStatus();

        this.currentItem = item;
        console.log('currentItem onClickPlaylistItem==>', this.currentItem)

        this.currentItemObs.next(this.currentItem);
        console.log('currentItemObs==>', this.currentItemObs, 'currentItemObs next==>', this.currentItemObs.next(this.currentItem));

    }

    private getMiliSecond(rawSeconds: any) {
        var seconds = 0;
        try 
        {
            //var formattedTime = this.datePipe.transform(rawSeconds, 'hh:mm:ss', '+0000') ;
            var formattedTime: any = this.datePipe.transform(rawSeconds, 'mm:ss', '+0000');
            console.log('formattedTime', formattedTime, rawSeconds);
    
            var a = formattedTime.split(':'); // split it at the colons
            // minutes are worth 60 seconds. Hours are worth 60 minutes.
            //var seconds = (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2]); 
            seconds = (+a[0]) * 60 + (+a[1]);
            console.log(seconds);
        }
        catch (error) 
        {
            console.log('Exception in getMiliSecond..........................',error);
        }
        return seconds;
    }

    updatePlayStatus() {
        var curretTime = this.media.time.current;
        console.log('curretTime==>', curretTime);

        var totalTime = this.media.time.total;
        console.log('totalTime==>', totalTime);

        var valuInPercent = parseInt(((curretTime / totalTime) * 100).toFixed());
        console.log('valuInPercent==>', valuInPercent);

        this.videoList = this.videoList.map((videoItem: any) => {
            console.log('videoItem===>', videoItem)
            if (this.currentItem.attachment === videoItem.attachment) {
                videoItem.accessPos = valuInPercent;
                console.log('accessPos of videoItem==>', videoItem.accessPos);

                //TO add and update accessStatus and accessPos for courseContentAtt Start
                var url = '/coursecontent/' + this.courseCodeData + '/' + this.currentItem.contentName
                console.log('url for courseContentAtt data', url);
                var courseContentStatus = videoItem.accessPos >= 100 ? 'C' : 'P';
                var accessPos = parseInt(videoItem.accessPos);

                var contentData = {
                    'accessStat': courseContentStatus,
                    'accessPos': accessPos
                };

                if (this.courseContentSubs) {
                    this.courseContentSubs.unsubscribe();
                }

                this.courseContentSubs = this.saveCourseAttData(url, contentData).subscribe(
                    (res: any) => {
                        console.log('saveCourseContentAttData in service', res)
                    }
                );
                //TO add and update accessStatus and accessPos for courseContentAtt End
            }
            return videoItem;
        });
    }

    //var docUsageData = {'DOC_ID' : this.content.docId, 'DOC_NAME' : this.content.docName, 'DOC_TYPE' : this.content.docType, 'USAGE_DETAIL_DATA' : videoUsage};

    logDocUsage(docUsageData: any) {
       let url = this.SERVICE_URL + '/LogDocUsage';
       // let headers = new Headers({ 'Content-Type': 'application/json' });
       let headers = new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded' });
       console.log('Doc Usage Data in video-api service', url, docUsageData);
        return this.http.post(url, JSON.stringify(docUsageData), { headers: headers });
    }

    saveCourseAttData(url: any, data: any) {
        url = this.SERVICE_URL + url;
        let headers = new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded' });
        console.log('saveCourseAttAData in video-api service', url, data);

        return this.http.post<any>(url, JSON.stringify(data), { headers : headers})
            .pipe(map((res: any) => this.extractData(res)));
    }

    closeQuestionForm() {
        this.dashboardService.onClose();
    }

    getUserInfo() {
        return this.dashboardService.getUserInfo();
    }

    sendCourseCert(courseCode: any):Observable<any> {
        var url = this.hosturl + this.CERT_URL+'/executeReportSendMail';
        console.log("url of attached file"+url);
        var data = {
        'OBJ_NAME':'d_ser_gyan_cert',
        'DATA_FORMAT':'d_ser_gyan_cert',
        'course_name': courseCode
        };
        let headers = new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded' });
        console.log('saveCourseAttAData in video-api service and attach PDF', url, data);
        return this.http.post<any>(url, JSON.stringify(data), { headers : headers })
        .pipe(map((res: any) => this.extractData(res)));
        }
}
