import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default () => new Vuex.Store({
    modules: {
        //
    },
    state: {
        user: {
            UID: null,
            name: 'Guest',
            type: 'guest',
            avatarFile: null,
            is_active_and_visible: true
        },
        session: {
            screenSharingAvailable: false,
            sessionConnected: false,
            screenSharingActive: false
        },
        meeting: {
            uid: null,
            lobby_uid: null,
            name: '',
            active_members: [],
            pros_online: []
        },
        lobbies: [],
        settings: {
            newMeetingNotificationExpanded: localStorage.getItem('newMeetingNotificationExpanded') == 'true' ? true : false,
            admin: {
                showAllLobbiesMettings: localStorage.getItem('showAllLobbiesMettings') == 'true' ? true : false
            }
        },
        meetingLoading: false,
        callToNoAnswer: null,
        callWidget: []
        // {
        //     active: false,
        //     noAnswer: false,
        //     callInfo: {}
        // }
    },
    mutations: {

        /* User */

        setInitialUser(state, data) {
            state.user = data
        },
        setUserAvatarFile(state, data) {
            state.user.avatarFile = data
        },
        setUserActivityState: (state, data) => {
            state.user.is_active_and_visible = data
        },

        /* Lobbies */

        setLobbies(state, data) {
            state.lobbies = data
        },
        addNewLobby(state, data) {
            state.lobbies.push(data)
        },
        updateLobby(state, data) {
            let lobby = state.lobbies.filter((cur) => cur.uid == data.uid)

            if (lobby.length) {
                for (let prop in data) {
                    lobby[0][prop] = data[prop]
                }
            }
        },
        activateLobby(state, data) {
            let lobby = state.lobbies.filter((cur) => cur.uid == data.uid)

            if (lobby.length) {
                lobby.isActive = true
            }
        },
        deactivateLobby(state, data) {
            let lobby = state.lobbies.filter((cur) => cur.uid == data.uid)

            if (lobby.length) {
                lobby.isActive = false
            }
        },

        setLobbyActivity(state, data) {
            if (!data || !data.lobby_uid) return
            let lobby = state.lobbies.filter((cur) => cur.uid == data.lobby_uid)
            if (lobby.length) {
                let meeting = lobby[0].meetings.filter((cur) => cur.uid == data.meeting_uid)

                if (meeting.length) {
                    meeting[0].active_members = Object.values(data.active_members)
                    meeting[0].pros_online = Object.values(data.pros_online)

                    if (state.meeting.uid && state.meeting.uid == meeting[0].uid) {
                        state.meeting.active_members = data.active_members
                    }

                    call = state.callWidget.find(c => c.callInfo.meeting_uid == meeting[0].uid)
                    if (call) {
                        if (!meeting[0].active_members.length || meeting[0].pros_online.findIndex((x) => x.uid == state.user.uid) !== -1) {
                            call.active = false
                        } else {
                            call.active = true
                        }
                    }
                }
            }
        },

        /* Meetings */

        addNewMeetingInLobby(state, data) {
            console.log(data)
            if (!data.lobby) return
            let lobby = state.lobbies.filter((cur) => cur.uid == data.lobby.uid)

            if (lobby.length) {
                data.active_members = []
                data.pros_online = []

                lobby[0].meetings.push(data)
                lobby[0].meetings.sort((a, b) => {
                    return a.finalDate - b.finalDate
                })
            }
        },
        setUpdatedMeetingInLobby(state, data) {
            let lobby = state.lobbies.filter((cur) => cur.uid == data.lobby.uid)

            if (lobby.length) {
                let meeting = lobby[0].meetings.filter((cur) => cur.uid == data.uid)

                if (meeting.length) {
                    for (let prop in data) {
                        meeting[0][prop] = data[prop]
                    }
                }
            }
            if (state.meeting.uid === data.uid) {
                state.meeting.name = data.name
            }
        },
        setCurrentMeeting(state, data) {
            state.meeting = data
        },
        nullifyMeetingsOnline(state) {
            for (let lobby of state.lobbies) {
                for (let meeting of lobby.meetings) {
                    meeting.active_members = []
                    meeting.pros_online = []
                }
            }

            state.callWidget.active = false
        },
        setMeetingLoadingState(state, data) {
            state.meetingLoading = data
        },

        /* Other */

        setCall(state, data) {
            const call = {
                active: false,
                timer: null,
                callInfo: null
            }
            call.callInfo = data

            if (call.callInfo.time_limit) {
                call.timer = setInterval(() => {
                    if (call.callInfo.time_limit > 0) {
                        call.callInfo.time_limit--

                        if (call.callInfo.time_limit == 0) {
                            clearInterval(call.timer)
                            call.timer = null
                            console.log('TIME IS OUT!')
                            const callIndex = state.callWidget.findIndex(c => c.uid === call.uid)
                            if (callIndex > -1)
                                state.callWidget.splice(callIndex, 1)
                            state.callToNoAnswer = call
                            $.ajax({
                                url: "/post-to-api-ajax",
                                method: "POST",
                                headers: {
                                    "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content")
                                },
                                data: {
                                    _api: "/api/meetingRing/ringNoAnswer",
                                    uid: call.callInfo.ring_uid
                                },
                                error: (jXhr) => console.log(jXhr)
                            })
                        }
                    }
                }, 1000)
            }

            if (data.lobby_call_uid)
                call.active = true
            state.callWidget.push(call)
        },
        rejectCall(state, call) {
            state.callWidget.active = false
            if (call.timer)
                clearInterval(call.timer)
            const callIndex = state.callWidget.findIndex(c => c.uid === call.uid)
            if (callIndex > -1)
                state.callWidget.splice(callIndex, 1)
            // state.callWidget.callInfo = {}
            // if (call.timer)
            //     clearInterval(timer)
        },
        setSessionConnectivityState(state, data) {
            state.session.sessionConnected = data
        },
        updateSettings(state, data) {
            state.settings = data
        }
    },
    actions: {
        leaveMeeting(store) {
            let meeting = {
                uid: null,
                lobby_uid: null,
                name: '',
                active_members: [],
                pros_online: []
            }

            store.commit('setCurrentMeeting', meeting)
        }
    }
})