import { create } from 'apisauce'
import Config from 'src/utils/Config'
import DeviceInfo from 'react-native-device-info'
import { Platform } from 'react-native'

const ApiPowerCondo = create({
  baseURL: Config.API_BASE_URL_POWER_CONDO_DEV,
  headers: {
    'X-Frame-Options': 'sameorigin',
    'X-App-Version': DeviceInfo.getVersion(),
    'X-Device-OS': Platform.OS,
    'X-Device-Version': Platform.Version,
    'Content-Type': 'application/json'
  }
})

DeviceInfo.getDeviceName().then(name => {
  ApiPowerCondo.setHeader('X-Device-Name', name)
})

ApiPowerCondo.addRequestTransform(request => {
  // request.headers['X-App-Locale'] = I18n.locale
})
if (process.env.NODE_ENV !== 'production') {
  ApiPowerCondo.addRequestTransform(request => {
    console.info('--> [' + request.method + '] ' + ApiPowerCondo.getBaseURL() + request.url, request.params, request.data)
    console.info('header --' + request.url + ' -- ', request.headers)
  })
  ApiPowerCondo.addMonitor(response => {
    console.info('<-- ' + response.status + ' --- ' + response.config.url, response)
  })
}

// error alert monitor
ApiPowerCondo.addMonitor(response => {
  if (!response.ok) {
    switch (response.problem) {
      case 'CONNECTION_ERROR':
      case 'NETWORK_ERROR':
      case 'TIMEOUT_ERROR':
        // Alert.alert('error_internet_title', 'error_internet_message', [{text: 'ok'}])
        break
      case 'SERVER_ERROR':
      case 'CANCEL_ERROR':
      case 'CLIENT_ERROR': // 4XX
        break
    }
  }
})

export function setTokenPowerCondo (token) {
  ApiPowerCondo.setHeader('Authorization', 'Bearer ' + token)
}

export function setLanguagePowerCondo (languageCode) {
  ApiPowerCondo.setHeader('language', languageCode)
}

export function clearTokenPowerCondo () {
  ApiPowerCondo.deleteHeader('Authorization')
}

export function setLocationPowerCondo (lat, lng) {
  ApiPowerCondo.setHeader('X-Current-Latitude', lat.toString() || '0.0')
  ApiPowerCondo.setHeader('X-Current-Longitude', lng.toString() || '0.0')
}

export default ApiPowerCondo
