// ==============================================================================
// создание promiseReducer
function promiseReducer(state = {}, { type, status, payload, error, nameOfPromise }) {
  if (type === 'PROMISE') {
    return {
      ...state,
      [nameOfPromise]: { status, payload, error }
    }
  }
  return state
}

// акшоны для promiseReducer
const actionPending = nameOfPromise => ({ nameOfPromise, type: 'PROMISE', status: 'PENDING' })
const actionFulfilled = (nameOfPromise, payload) => ({ nameOfPromise, type: 'PROMISE', status: 'FULFILLED', payload })
const actionRejected = (nameOfPromise, error) => ({ nameOfPromise, type: 'PROMISE', status: 'REJECTED', error })
const actionPromise = (nameOfPromise, promise) =>
  async dispatch => {
    dispatch(actionPending(nameOfPromise)) //сигнализируем redux, что промис начался
    try {
      const payload = await promise //ожидаем промиса
      dispatch(actionFulfilled(nameOfPromise, payload)) //сигнализируем redux, что промис успешно выполнен
      return payload //в месте запуска store.dispatch с этим thunk можно так же получить результат промиса
    }
    catch (error) {
      dispatch(actionRejected(nameOfPromise, error)) //в случае ошибки - сигнализируем redux, что промис несложился
    }
  }

// =============================================================
// функция getGql
function getGql(endpoint) {
  return async function gql(query, variables = {}) {

    let headers = {
      'Content-Type': 'application/json;charset=utf-8',
      'Accept': 'application/json',
    }
    if (('authToken' in localStorage)) {
      headers.Authorization = 'Bearer ' + localStorage.authToken
    }

    let result = await fetch(endpoint, {
      method: 'POST',
      headers,
      body: JSON.stringify({
        query,
        variables
      })
    }).then(res => res.json())

    if (('errors' in result) && !('data' in result)) {
      throw new Error(JSON.stringify(result.errors))
    }

    result = Object.values(result.data)[0]

    return result
  }
}

const gql = getGql('http://hipstagram.node.ed.asmer.org.ua/graphql')



export const actionFindPostOne = _id => actionPromise('PostFindOne', gql(`query OnePostFind ($postOne: String){
  PostFindOne (query: $postOne) {
    _id createdAt title text likesCount
    images {
      url
    }
    comments {
      _id createdAt text answers {
        _id createdAt text likes {
          _id
        }
        likesCount owner {
          _id login nick  avatar {
            _id url
          }
        }
      }
      likesCount
    }
    owner {
      _id login nick
    }
    
  }
}`, {
  postOne: JSON.stringify([{ _id }])
}))


export const actionFindUserOne = _id => actionPromise('UserFindOne', gql(`query OneUserFind ($userOne: String) {
  UserFindOne(query: $userOne) {
    _id createdAt login nick 
    avatar {
      _id url
    } 
     followers {
      _id login nick avatar {_id url}
    }
    following {
       _id login nick avatar {_id url}
    }
  }
}`, {
  userOne: JSON.stringify([{ _id }])
}))