import Axios from 'axios';
import { PageList } from '../pages/Router';
import app from '../../app.json';

//config
//const hostUrl = 'http://161.117.183.142/';
const hostUrl = app.product ? 'https://csms.chargeco.global/' : 'https://uat.chargeco.global/';
const service = 'chargeco/'
export const host = hostUrl;

const DEBUG = app.debug && !app.product;

Axios.defaults.timeout = 10000;
Axios.interceptors.response.use((response) => {
  if (DEBUG) {
    console.log('-------', response.config.method, response.config.url);
    console.log('-------', JSON.stringify(response.data));
    console.log('-------', response.status);
  }
  if (response.data.code == '401' || response.data.code == '402') {
    setAccessToken('');
    startPage(PageList.login, {action: response.data.code});
    return Promise.reject('Need sign in');
  }
  if (response.data.code == '500' || response.data.code == '502') {
    setAccessToken('');
    return Promise.reject('Sever error');
  }
  return response.data;
}, (error) => {
  console.info('-------error', error);
  return Promise.reject(error);
});

export const get = (path, params) => {
  return new Promise((resolve, reject) => {
    Axios.get(host + service + path, {
      params: params,
      method: 'GET',
      headers: {
        'Accept': 'application/json',
        'lang': global.currentLocale,
        'accessToken': global.accessToken ?? ''
      }
    }).then(res => {
      if (res.success) {
        resolve(res);
      } else if (res.msg) {
        reject({err: res.msg, ...res});
      } else {
        reject('Request Failed');
      }
    }).catch(error => {
      console.info('HTTP-ERROR', error);
      reject(error);
    });
  });
}

export const post = (path, params) => {
  return new Promise((resolve, reject) => {
    Axios.post(host + service + path, params, {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'lang': global.currentLocale,
        'accessToken': global.accessToken ?? ''
      }
    }).then(res => {
      if (res.success) {
        resolve(res);
      } else if (res.msg) {
        reject({err: res.msg, ...res});
      } else {
        reject('Request Failed');
      }
    }).catch(error => {
      console.info('HTTP-ERROR', error);
      reject(error);
    });
  });
}

export const upload = (path, params, header) => {
  return new Promise((resolve, reject) => {
    Axios.post(host + service + path, params, {
      method: 'POST',
      headers: {
        'lang': global.currentLocale,
        'Accept': 'application/json',
        'Content-Type': 'multipart/form-data',
        'accessToken': global.accessToken ?? '',
        ...header
      }
    }).then(res => {
      if (res.success) {
        resolve(res);
      } else if (res.msg) {
        reject({err: res.msg, ...res});
      } else {
        reject('Request Failed');
      }
    }).catch(error => {
      console.info('HTTP-ERROR', error);
      reject(error);
    });
  })
}

export const GET = (url, params) => {
  var request = host + service + url;
  if (params) {
    var keys = ''
    for (let key in params) {
      if (keys != '') {
        keys += '&';
      }
      keys += key + '=' + encodeURI(params[key]);
    }
    if (keys !== '') {
      request += '?' + keys;
    }
  }
  return new Promise((resolve, reject) => {
    fetch(request, {
      method: 'GET',
      headers: {
        'lang': global.currentLocale,
        'Accept': 'application/json',
        'accessToken': global.accessToken ?? ''
      }.then((response) => {
        if (response.ok) {
          return response.json();
        } else {
          reject(response);
        }
      }).then(data => {
        resolve(data);
      }).catch((error) => {
        reject(error);
      })
    });
  });
}

export const POST = (url, params) => {
  return new Promise((resolve, reject) => {
    fetch(host + service + url, {
      method: 'POST',
      headers: {
        'lang': global.currentLocale,
        'Accept': 'application/json',
        'content-type': 'application/json',
        'accessToken': global.accessToken ?? ''
      },
      body: JSON.stringify(params)
    }).then((response) => {
      if (response.ok) {
        return response.json();
      } else {
        reject(response);
      }
    }).then(data => {
      resolve(data);
    }).catch((error) => {
      reject(error);
    })
  });
}

export const SOCKET = (url) => {
  const ws = new WebSocket(url); // like 'wss://vbea.com/path'

  ws.onopen = () => {
    // connection opened
    ws.send('something'); // send a message
  };

  ws.onmessage = (e) => {
    // a message was received
    console.log(e.data);
  };

  ws.onerror = (e) => {
    // an error occurred
    console.log(e.message);
  };

  ws.onclose = (e) => {
    // connection closed
    console.log(e.code, e.reason);
  };
}

export const setAccessToken = token => {
  global.accessToken = token;
}