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

// import { strings as t } from '../i18n'
// import { userLogout } from 'src/redux/app/action'
// import I18n from 'i18n-js'

let store

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

export function setBaseUrl (baseUrl) {
  Api.setBaseURL(baseUrl)
}

export function setBaseUrlByServerMode (mode) {
  // Api.setBaseURL(mode === 'production' ? Config.API_BASE_URL_PROD : Config.API_BASE_URL_DEV)
  Api.setBaseURL(mode === 'production' ? Config.API_BASE_URL_POWER_CONDO_PROD : Config.API_BASE_URL_POWER_CONDO_DEV)
}

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

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

// error alert monitor
Api.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
        /*if (response.status === 401) {
          Alert.alert('Session timeout', 'Please login again to continue using application', [
            {
              text: 'ok',
              onPress: () => {
                // NavigationService.navigate('AppLoading')
              }
            }
          ], { cancelable: false })
          return
        }*/
        // Alert.alert(null, 'error_getting_data', [{text: 'ok'}])
        break
    }
  }
})

export function setStore (reduxStore) {
  store = reduxStore
}

export function setToken (token) {
  Api.setHeader('Authorization', 'Bearer ' + token)
}

export function setLanguage (languageCode) {
  Api.setHeader('language', languageCode)
}

export function clearToken () {
  Api.deleteHeader('Authorization')
}

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

export default Api
