
import DateFunction from "../../../core/helpers/date/DateFunction";
import {axiosGet, urlGenerator} from "../../../application/helpers/AxiosHelper";
import * as actions from "../../../application/config/ApiUrl";

export default {
    state: {
        loggedInUser: { uuid: window?.user?.uuid },
        profile_picture: '',
        users: [],
        socialLinks: [],
    },

    getters: {
        getUsers: state => state.users,
        loggedInUser: state => state.loggedInUser,
    },

    mutations: {
        SET_USERS(state, data) {
            state.users = data
        },
        GET_USER(state, obj) {
            const {rootState, user} = obj;
            state.loggedInUser = user;

            if (user.profile) {
                state.loggedInUser.date_of_birth = user.profile.date_of_birth ? new Date(user.profile.date_of_birth) : null;
                state.loggedInUser.gender = user.profile?.gender;
                state.loggedInUser.contact = user.profile?.contact;
                state.loggedInUser.address = user.profile?.address;
                state.loggedInUser.about = user.profile?.about;
            }

            state.loggedInUser.created_at = DateFunction.getDateFormat(user.created_at, rootState.settings.dateFormat);
            state.loggedInUser.role = user.roles && user.roles.length ? user.roles[0].name : '';
            state.profile_picture = user.profile_picture?.full_url ? user.profile_picture.full_url : urlGenerator('/images/avatar-demo.jpg');
            state.loggedInUser.img = user.profile_picture?.full_url ? user.profile_picture.full_url : urlGenerator('/images/avatar-demo.jpg');
            state.socialLinks = user?.social_links.filter((item, index) => {
                item.link = item.pivot.link;
                item.edit = false;
                return item;
            });
        },
    },

    actions: {
        getUser({commit, rootState}) {
            axiosGet(actions.AUTHENTICATE_USER).then(res => {
                const obj = {
                    user: res.data,
                    rootState
                };
                commit('GET_USER', obj);
            });
        },
        addUser({commit, state}, user) {
            commit('SET_USERS', state.users.concat([user]));
        },
        getUsers({commit, state}, payload = {}) {
            const url = payload.users ? `${actions.GET_USERS}?existing=${payload.users}` : actions.GET_USERS;
            axiosGet(url).then(({data}) => {
                commit('SET_USERS', data)
            });
        },
    }
}
