import Vue from 'vue'
import Axios from 'axios'

// export default function(store, req) {
  const service = Axios.create({
    withCredentials: true,
    baseUrl: '/'
  })
  service.interceptors.request.use(config => {
    config.url = config.url || '/'
    if (process.server) {
      // const cookie = config.req.headers['cookie']
      // store.commit('option/SET_COOKIES', cookie)
      if (config.url.indexOf('.') === -1) {
        config.url = process.env.baseUrl + config.url
      }
      // config.headers.cookie = store.state.option.cookies + '; ' +  store.state.option.sessionId
      // config.headers['User-Agent'] = store.state.option.userAgent
    }
    // console.log(config.url)
    // if (typeof window === 'undefined') {
      // config.headers.cookie = store.state.option.cookies + '; ' + store.state.option.sessionId
      // // config.headers['User-Agent'] = Vue.$store.state.option.userAgent
    // } else {
      // console.log(store)
    // }
    return config
  }, error => {
    return Promise.reject(error)
  })

  service.interceptors.response.use(response => {
    const cookies = response.headers['set-cookie']
    if (cookies && cookies.length) {
      for (let i = 0; i < cookies.length; i++) {
        if (cookies[i].indexOf('JSESSIONID') > -1) {
          const sessionId = cookies[i]
          const first = sessionId.indexOf(';')
          const second = sessionId.lastIndexOf(';')
          const newSessionId = sessionId.replace(sessionId.substring(first, second), '')
          store.commit('option/SET_SESSION_ID', newSessionId)
          break
        }
      }
    }
    return response
  }, error => {
    return Promise.reject(error)
  })

  Vue.prototype.$http = service
export default service

// }

// export default function ({ isServer, store, req }) {
//   axios(store, req)
// }

