import axios from 'axios';
import AsyncStorage from '@react-native-community/async-storage';
const baseUrl = 'https://gb-api.azurewebsites.net/api/v1.0/Integrations';
var playerId = ''


async function getPlayerId() {
  const id = await AsyncStorage.getItem('gameball_player_id')
  playerId = id;
  return id;
}

const addReferral = (data) => {
  return makeRequest(baseUrl + '/Referral', data);
}

async function sendEvent(data) {

  const sendEventJson = {
    "events": data,
    "playerUniqueId": await AsyncStorage.getItem('gameball_player_id')
  }
  return makeRequest(baseUrl + '/Action', sendEventJson);

}
async function registerUser(data) {
  playerId = data.playerUniqueId;
  // console.log(playerId)
  await AsyncStorage.setItem('gameball_player_id', playerId)
  return makeRequest(baseUrl + '/InitializePlayer', data);
}

async function makeRequest(url, data) {
  let apiKey = await AsyncStorage.getItem('gameball_apikey');
  var config = {
    headers: {
      APIKey: apiKey,
    }
  };
  console.log(data, apiKey)
  // axios.interceptors.request.use(request => {
  //   console.log('Starting Request', request)
  //   return request
  // })

  return axios.post(url, data, config);
};
const getReferralCode = (url) => {
  let index = url.indexOf("=");
  index = index + 1;
  return (url.substring(index))
}
export {
  registerUser,
  addReferral,
  sendEvent,
  getPlayerId,
  getReferralCode
}
