const actions = {
    // Video ended    
    ended({dispatch,commit}, video) {
        video.isPlaying = false;        
        dispatch('next', video);
        commit('PLAYING',video);
    },

    // Add video to queue
    addToQueue({state, dispatch, commit }, obj) {
        var index = _.findIndex(state.queue, function(o) {
            return o.videoId == obj.videoId; });
        if (index == -1) commit('ADD_TO_QUEUE', obj);
    },

    // Play a video
    playVideo({ state, dispatch, commit }, video) {        
        if (!state.playing || state.playing.videoId != video.videoId) {
            state.player.loadVideoById({ videoId: video.videoId, suggestedQuality: 'small' });            
        } else {            
            state.player.playVideo();
        }
        video.isPlaying = true;
        commit('PLAYING',video);                
        dispatch('addToQueue', video);        
    },

    // Puase a video
    pauseVideo({ state, dispatch, commit }, video) {        
        video.isPlaying = false;        
        state.player.pauseVideo();
        commit('PLAYING',video);
    },

    // Play next song
    next({ state, dispatch, commit }) {
        if (state.queue && state.playing) {            
            var index = _.findIndex(state.queue, function(o) {
                return o.videoId == state.playing.videoId; 
            });            
            if (index != -1 && state.queue[index + 1]) {                
                dispatch('playVideo', state.queue[index + 1]);
            }
        }        
    },

    // Play previous song
    previous({ state, dispatch, commit }) {
        if (state.queue && state.playing) {
            var index = _.findIndex(state.queue, function(o) {
                return o.videoId == state.playing.videoId; 
            });
            if (index && state.queue[index - 1]) {
                dispatch('playVideo', state.queue[index - 1]);
            }
        }
    },
    addToFav({state,commit},video){        
        var index = _.findIndex(state.favs,function(o){            
            return o.videoId == video.videoId;
        });
        // Add to favs if not exists                
        if(index == -1) {
            commit('ADD_TO_FAVS',video);
            state.localStorage.setItem("favs", state.favs);
        } else if(index >= 0) {
            commit('REMOVE_FROM_FAVS',index);
            state.localStorage.setItem("favs", state.favs);        
        }
    },
    // Add localforge to state and load data from localStorage
    loadLocalStorage({state,commit},localStorage){
        commit('LOAD_LOCAL_STORAGE',localStorage);
        state.localStorage.getItem('favs').then(function(list) {            
            if(list) commit('ADD_TO_FAVS',list);
        }).catch(function(err) {    
            console.log(err);
        });
    }    
}

export default actions;