//jetpack fix
_.contains = _.includes;
window.lodash = _.noConflict();

window.addEventListener('load', YMVI_pageImportVideos, false);
function YMVI_pageImportVideos() {

    if(document.getElementById('import-videos')){

        jQuery('body').tooltip({ selector: '[rel=tooltip]', container: 'body', trigger : 'hover' });

        //resize thumbs
        var resizeThumbs = function(){
            if( jQuery('.video-img-block:first').length > 0 && importVideos.displayType == 'cards' ){
                var $firstThumb     = jQuery('.video-img-block:first');
                var refthumbWidth  = $firstThumb[0].getBoundingClientRect().width;
                jQuery('.video-img-block img').css('max-width', refthumbWidth).css('height', refthumbWidth * 3 / 4 );
            }
        };

        //sticky header
        if( jQuery('#videos-found').length > 0 )  {
            var $headerNav = jQuery('#videos-found-header');
        }

        var stickNav = function(){
            if( jQuery('#videos-found').is(':visible') )  {
                var stickyNavTop = jQuery('#videos-found').offset().top - $headerNav.height() - 32;
                var scrollTop = jQuery(window).scrollTop()
                var $totalWidth = jQuery('#import-videos').width();
                if (scrollTop > stickyNavTop ) {
                    jQuery('#videos-found-header').addClass('sticky').width($totalWidth);
                    jQuery('#sticky-space').height('96px');
                } else {
                    jQuery('#videos-found-header').removeClass('sticky');
                    jQuery('#videos-found-header').width('100%');
                    jQuery('#sticky-space').height('0px');
                }
            }
        };

        //on window load / scroll / resize
        jQuery(window).on('load scroll resize', function(e) {
            stickNav();
        });

        jQuery(window).on('resize', function(e) {
            resizeThumbs();
        });

        //vue script
        var importVideos = new Vue({
            el: '#import-videos',
            data: {
                //loading
                loading : {
                    loadingData         : false
                },
                ///data
                dataLoaded : false,
                data : {},

                //misc
                displayType : 'cards',

                //pagination
                nextPageToken: '',

                //filters
                showFilters : false,
                filters : {
                    publishedAfter: 'any',
                    type: 'video',
                    videoDuration: 'any',
                    features: 'any',
                    order: 'relevance'
                },

                //categories & keywords
                selectedKW  : '',
                selectedWPCat : 0,

                //videos
                videos : [],
                searchingVideos : false,
                videosHasBeenSearched : false,
                videosSearchedErrors : null,

                currentVideo : '',
                currentVideoEmbed : '',

                importingVideos : false,
                savedCheckedVideosCounter : 0
            },
            computed: {
				selectedKWPlaceholder: function() {
					switch (this.filters.type) {
						case 'channel':
							return 'Paste a Channel ID (eg. UC_7s69e1mDS3lgcTMJEPjCg)';
						case 'playlist':
							return 'Paste a Playlist ID (eg. PLp_G0HWfCo5rJsCeNMuuYCoqUmPa5M2YX)';
						case 'video':
						default:
							return 'Enter some Keywords (eg. Katy Perry)';
					}
				},
				typeDetectedFromKW: function() {
					switch (this.selectedKW.slice(0, 2).toUpperCase()) {
						case 'UC':
							return 'channel';
						case 'PL':
							return 'playlist';
						case 'video':
						default:
							return 'video';
					}

				},
                siteIsHttps : function(){
                    return window.location.protocol == "https:";
                },
                checkedVideosCounter : function(){
                    return this.videos.filter( function(video){
                        return video.checked;
                    }).length;
                },
                selectedWPCatName : function(){
                    self = this;
                    if(this.selectedWPCat > 0){
                        return lodash.find(self.data.WPCats, function(wpcat){
                            return wpcat.term_id == self.selectedWPCat;
                        }).name;
                    }
                    return '...';
                },
                importProgress : function(){
                    var progress = ( this.savedCheckedVideosCounter - this.checkedVideosCounter ) / this.savedCheckedVideosCounter * 100;
                    if( this.importingVideos ){
                        return progress >= 100 ? 100 : progress;
                    }
                    return 0;
                },
                checkableVideosCounter : function(){
                    return this.videos.filter( function(video){
                        return !video.grabbed && !video.blocked;
                    }).length;
                },
                allVideosChecked : function(){
                    return ( ( this.checkedVideosCounter == this.checkableVideosCounter ) && ( this.checkableVideosCounter > 0 ) );
                },
                videosCounter : function(){
                    return this.videos.length;
                },
                searchBtnClass : function(){
                    if( this.selectedKW == '' ){
                        return 'disabled';
                    }
                    return '';
                },
                importBtnClass : function(){
                    if( this.checkedVideosCounter <= 0 || this.selectedWPCat == 0 || this.importingVideos ){
                        return 'disabled';
                    }
                    return '';
                },
                importButtonTooltip : function(){
                    var title = '';
                    if( this.selectedWPCat == 0){
                        title += this.data.objectL10n.select_wp_cat;
                    }
                    if( this.checkedVideosCounter == 0 && this.selectedWPCat == 0 ){
                        title += ' ' + this.data.objectL10n.and + ' ';
                    }
                    if( this.checkedVideosCounter == 0){
                        title += this.data.objectL10n.check_least;
                    }
                    if( this.checkedVideosCounter == 0 || this.selectedWPCat == 0 ){
                        title += ' ' + this.data.objectL10n.enable_button;
                    }
                    if( !this.importingVideos )
                        return title;

                    return '';
                },
            },
            filters:{
                formatTime : function( timeInSeconds ){
                    var date = new Date(1970,0,1);
                    date.setSeconds(timeInSeconds);
                    return date.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/, "$1");
                },
                formatFeatures : function( features ){
                    var output = '';
                    if( features['3D'] )  output += '<span class="label label-warning">3D</span>' + String.fromCharCode(13);
                    if( features['360'] ) output += '<span class="label label-info">360°</span>' + String.fromCharCode(13);
                    if( features['CC'] )  output += '<span class="label label-default">CC</span>' + String.fromCharCode(13);
                    if( features['HD'] )  output += '<span class="label label-danger">HD</span>' + String.fromCharCode(13);
                    return output;
                },
                listFormat : function( list ){
                    return list.replace(/;/g, ',').split(',').join(', ');
                },
                addZero : function( number ){
                    if( number < 10 )
                        number = '0' + number;
                    return number;
                }
            },
            methods: {
				noVideoFoundErrorMessage: function() {
					var messages = {
						video: {
							video: 'There is no video for this search',
							channel: 'The keyword you have entered doesn\'t look like a Channel ID (eg. UC_7s69e1mDS3lgcTMJEPjCg)',
							playlist: 'The keyword you have entered doesn\'t look like a Playlist ID (eg. PLp_G0HWfCo5rJsCeNMuuYCoqUmPa5M2YX)',
						},
						channel: {
							video: 'If you want to search videos from a <code>Channel</code>, click on <code>Filters</code> and select <code>TYPE > Channel</code>',
							channel: 'This Channel ID doesn\t exist. Be sure you have not misspelled it (eg. UC_7s69e1mDS3lgcTMJEPjCg)',
							playlist: 'If you want to search videos from a <code>Channel</code>, click on <code>Filters</code> and select <code>TYPE > Channel</code>',
						},
						playlist: {
							video: 'If you want to search videos from a <code>Playlist</code>, click on <code>Filters</code> and select <code>TYPE > Playlist</code>',
							channel: 'If you want to search videos from a <code>Playlist</code>, click on <code>Filters</code> and select <code>TYPE > Playlist</code>',
							playlist: 'This Playlist ID doesn\t exist. Be sure you have not misspelled it (eg. PLp_G0HWfCo5rJsCeNMuuYCoqUmPa5M2YX)',
						},
					};
					if ( ! messages[this.typeDetectedFromKW] && ! messages[this.typeDetectedFromKW][this.filters.type] ) {
						return 'There is no video for this search';
					}
					return messages[this.typeDetectedFromKW][this.filters.type];
				},
                toggleFilters : function(){
                    this.showFilters = !this.showFilters;
                },
                updateFilter : function( filterId, filterValue ){
                    this.filters[filterId] = filterValue;
                    this.searchVideos( false );
                },
                updateDisplayType : function( displayType ){
                    this.displayType = displayType;
                },
                resetSearch: function(){
                    this.videos = [];
                    this.videosHasBeenSearched = false;
                    this.selectedKW             = '';
                    this.checkedVideosCounter   = '';

                    jQuery('#cat_wp_select').selectpicker('val', '0');
                },
                searchVideos : function( more ){

                    if( this.selectedKW == '' ){
                        return false;
                    }

                    this.searchingVideos = true;
                    this.videosHasBeenSearched = false;
					this.videosSearchedErrors = null;

                    //reset searching states
                    if( !more ){
                        this.nextPageToken = '';
                        this.videos = [];
                    }

                    //reset tooltips states
                    //jQuery('[rel=tooltip]').tooltip('hide');

                    this.$http.post(
                        YMVI_import_videos.ajax.url,
                        {
                            action          : 'YMVI_search_videos',
                            kw              : this.selectedKW,
                            limit           : this.data.videosLimit,
                            nonce           : YMVI_import_videos.ajax.nonce,
                            filters         : this.filters,
                            pageToken       : this.nextPageToken
                        },
                        {
                            emulateJSON: true
                        })
                    .then(function(response){
                            var videos = this.videos;
							if ( response.body.code ) {
                            	this.videosSearchedErrors = response.body;
							} else {
                                this.nextPageToken = response.body.nextPageToken;
                                lodash.each( response.body.videos, function(video){
                                    videos.push(video);
                                });
                            }
                            delete response;
                            delete videos;
                    }, function(response){
                        // error callback
                        console.error(response);
                    }).
                    then( function() {

                        this.videosHasBeenSearched = true;
                        this.searchingVideos = false;

                        stickNav();
                        var delay = setTimeout(function(){
                            resizeThumbs();
                        }, 1000);

                    });
                },
                toggleVideo : function(index, from){
                    this.videos[index].checked = ! this.videos[index].checked;
                },
                toogleAllVideos : function(){
                    var allVideosChecked = ! this.allVideosChecked;
                    lodash.each( this.videos, function(video){
                        if(!video.grabbed && !video.blocked){
                            video.checked = allVideosChecked;
                        }
                    });
                },
                setCurrentVideo : function(video, index){
                    this.currentVideo       = video;
                    this.currentVideoEmbed  = video.embed;
                    this.currentVideo.index = index;
                },
                prevVideoModal : function(index){
                    if( index <= 0 ){
                        this.currentVideoEmbed    = this.videos[this.checkableVideosCounter - 1].embed;
                        this.currentVideo.index   = this.checkableVideosCounter - 1;
                    }else{
                        this.currentVideo         = this.videos[index - 1];
                        this.currentVideoEmbed    = this.videos[index - 1].embed;
                        this.currentVideo.index   = index - 1;
                    }

                },
                nextVideoModal : function(index){
                    if( index >= this.checkableVideosCounter - 1){
                        this.currentVideo         = this.videos[0];
                        this.currentVideoEmbed    = this.videos[0].embed;
                        this.currentVideo.index   = 0;
                    }else{
                        this.currentVideo         = this.videos[index + 1];
                        this.currentVideoEmbed    = this.videos[index + 1].embed;
                        this.currentVideo.index   = index + 1;
                    }
                },
                importVideos : function(){
                    if( this.importBtnClass == 'disabled' ){
                        return;
                    }

                    //doing DOM stuff...
                    jQuery('#videos-found .progress-bar').removeClass('no-anim');
                    jQuery('.menu-icon-post .wp-menu-name').append(' <span class="update-posts"><span class="plugin-count"></span></span>');

                    //reset tooltips states
                    jQuery('[rel=tooltip]').tooltip('hide');

                    var checkedVideosCounter    = this.savedCheckedVideosCounter = this.checkedVideosCounter;
                    var cat_wp                  = this.selectedWPCat;
                    var self                    = this;

                    this.videos.filter( function(video){
                        return video.checked;
                    }).forEach( function(video){
                        self.importingVideos = true;
                        self.$http.post(
                            YMVI_import_videos.ajax.url,
                            {
                                action      : 'YMVI_import_video',
                                nonce       : YMVI_import_videos.ajax.nonce,
                                cat_wp      : cat_wp,
                                video_infos : video
                            },
                            {
                                emulateJSON: true
                            })
                        .then(function(response) {
                            if( response.body === -1 ){
                                console.error(response);
                            }
                            // success callback
                            video.grabbed = true;
                            video.checked = false;
                            // display post creation notice
                            jQuery('.update-posts .plugin-count').text('+ ' + (self.savedCheckedVideosCounter - self.checkedVideosCounter));

                        }, function(response) {
                            // error callback
                            console.error(response);
                        }).then( function() {
                            if( --checkedVideosCounter <= 0 ){
                                jQuery('#videos-found .progress-bar').addClass('no-anim');
                                jQuery('#videos-found .progress').addClass('finished');
                                var delay = setTimeout(function(){
                                    jQuery('#videos-found .progress').removeClass('finished');
                                    jQuery('.update-posts').remove();
                                    self.importingVideos = false;
                                }, 2000);

                            }
                        });
                    });
                }
            },
            mounted: function(){
                this.loading.loadingData = true;
                var self = this;
                this.$http.post(
                    YMVI_import_videos.ajax.url,
                    {
                        action        : 'YMVI_load_import_videos_data',
                        nonce         : YMVI_import_videos.ajax.nonce
                    },
                    {
                        emulateJSON: true
                    })
                .then((response) => {
                    // success callback
                    this.data = response.body;
                }, (response) => {
                    // error callback
                    console.error(response);
                }).then( _ => {
                    this.loading.loadingData = false;
                    this.dataLoaded = true;
                });

                this.resetSearch();

                //stop video when video modal is hidden
                jQuery('body').on('hidden.bs.modal', '#video-preview-modal', function (e) {
                    self.currentVideoEmbed = '';
                });

                //stop video when youtube api key modal is hidden
                jQuery('body').on('hidden.bs.modal', '#youtube-api-modal', function (e) {
                    jQuery("#youtube-api-key-video")[0].contentWindow.postMessage('{"event":"command","func":"stopVideo","args":""}', '*');
                });

                jQuery('body').on('shown.bs.tab', 'a[data-toggle="tab"]', function (e) {
                    if( jQuery( e.relatedTarget ).attr('href') == '#current-video-data' ){
                        self.currentVideoEmbed  = '';
                    }else{
                        self.currentVideoEmbed  = self.currentVideo.embed;
                    }
                });
            },
            watch: {
                selectedWPCat: function( newWPCat ){
                    if( '+' == newWPCat ){
                        this.selectedWPCat = '0';
                        jQuery('#add-wp-cat-modal').modal('show');
                        jQuery('#cat_wp_select').selectpicker('val', '0');
                    }
                }
            },
            directives: {
                img: {
                    inserted: function (el, arg) {
                        // Focus the element
                        var img = new Image();
                        img.src = arg.value;
                        img.onload = function() {
                            el.src = arg.value;
                            var thumbWidth = jQuery(el)[0].getBoundingClientRect().width;
                            if( this.displayType == 'cards'){
                                jQuery(el).css('opacity', 0).css('max-width', thumbWidth ).css('height', thumbWidth * 3 / 4 ).animate({ opacity: 1 }, 300);
                            }else{
                                jQuery(el).css('opacity', 0).animate({ opacity: 1 }, 300);
                            }
                        }
                    }
                }
            },
            components: {
                'bootstrap-select':{
                    props: ['value', 'options'],
                    template: `
                        <select>
                            <slot></slot>
                        </select>
                    `,
                    mounted: function(){
                        var vm = this;
                        jQuery(this.$el).selectpicker( this.options ).on('rendered.bs.select', function() {
                            vm.$emit('input', this.value);
                        });
                    },
                    destroyed: function(){
                        jQuery(this.$el).selectpicker('destroy');
                    }
                },
            }
        });
    }
};
