import Cookies from 'js-cookie';
import AuthService from '@/services/resources/AuthService';
import LogoutService from '@/services/resources/LogoutService';

export default {

//fazer login do OAuth 2
	loginRequest(context, payload){
        var service = AuthService.build();
		return new Promise((resolve, reject) => {
            
           service.login(payload.username,payload.password, payload.remember)
            .then((resp) => {
              
                let access_token = 'Bearer ' + resp.access_token;
                Cookies.set('access_token', access_token, { expires:  payload.remember ? 365 : 1 });
                
                context.commit('authSuccess', access_token);
               context.dispatch('userRequest');
                resolve(access_token);
            })
            .catch((err) => {
                context.commit('authError', err);
                Cookies.remove('access_token');
                reject(err);
            })
        })

  },
//Fazer login como outro usuário
    authRequestWhitUser(context, payload){

        return new Promise((resolve, reject) => {

            
            let actionUrl = "/api/user-get-token";
            let remember = false;
            let data = {
                user_id: payload.user_id,
            };
            axios.post(actionUrl, data)
            .then((resp) => {
                let access_token = 'Bearer ' + resp.data.access_token;
                Cookies.set('access_token', access_token, { expires: remember ? 365 : 1 });
                axios.defaults.headers.common['Authorization'] = access_token;

                context.commit('authSuccess', access_token);
                context.dispatch('userRequest');
                resolve(access_token);
            })
            .catch((err) => {
                
                reject(err);
            })
        })

  },

  logoutRequest: ({commit, dispatch}) => {
    var service = LogoutService.build();
    
      return new Promise((resolve, reject) => {
         
          service.get("")
          .then((resp) => {
            Cookies.remove('access_token');
            commit('authLogout');
            commit('userLogout');
            resolve(resp);
        })
        .catch((err) => {
            reject(err);
        });
    })

}
}