import $ from 'jquery'; 
import ICATPLUS from '../config/icat/icatPlus.js';
import { fetchMyInvestigations, fecthEmbargoedInvestigations, fecthReleasedInvestigations, fecthInvestigationsAsInstrumentScientist } from './investigations.js';
import { fetchDataCollections } from './datacollections.js';
import {
  LOG_IN,
  LOGGED_IN,
  LOG_OUT,
  LOGIN_ERROR
} from '../constants/ActionTypes'


export function doLogOut(user) { 
  return {
    type: LOG_OUT,
    user
  };
}


export function setLoginInfo(user) {
  return {
    type: LOGGED_IN,
    user
  };
}

export function doSignIn(plugin, username, password) {  
  return function (dispatch) {
               $.ajax({		
                  url: ICATPLUS.server + "/session",		
                  data: { 
                      "plugin"   : plugin,
                      "username" : username,
                      "password" : password       
                   },		
                  type: "post",	dataType : "json",		
                  beforeSend : function(){
                      dispatch({type: LOG_IN, username: username});  
                  },  
                  success: function( data ) {	                      	                   
                      if (data){
                        if (data.sessionId){                                                      
                            dispatch({type: LOGGED_IN, fullName: data.fullName, lifeTimeMinutes : data.lifeTimeMinutes, name : data.name, username: username, isAdministrator: data.isAdministrator, sessionId: data.sessionId});                                                    
                            dispatch(fecthEmbargoedInvestigations(data.sessionId)); 
                            dispatch(fecthReleasedInvestigations(data.sessionId));  
                            dispatch(fecthInvestigationsAsInstrumentScientist(data.sessionId));  
                              
                            dispatch(fetchMyInvestigations(data.sessionId));
                            dispatch(fetchDataCollections(data.sessionId));
                            
                        }
                      }                      
                  },			
                  error: function(error) {                       
                      dispatch({type: LOGIN_ERROR, username: username, error : "Authentication Failed" }); 
                  }
            });


   
  };
}