import {actionPromise} from "../reducers/reducers";
import {connect} from "react-redux";

//---------------------------------------getGql---------------------------------------------
const getGql = url =>
    (query, variables) => fetch(url, {
        method: 'POST',
        headers: {
            "Content-Type": "application/json",
            ...(localStorage.authToken ? { "Authorization": "Bearer " + localStorage.authToken } : {})
        },
        body: JSON.stringify({ query, variables })
    }).then(res => res.json())
        .then(data => {
            if (data.data) {
                return Object.values(data.data)[0]
            }
            else throw new Error(JSON.stringify(data.errors))
        })

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

//---------------------------------------Action---------------------------------------------
export const actionGetAboutMe = (id) =>
    actionPromise('aboutMe', gql(`query userOned($myID:String!){
                        UserFindOne(query: $myID){
                            _id  login nick
                            avatar { _id url }
                            following{ _id}
                        }
                }`, { myID: JSON.stringify([{ _id: id }]) }))

export const actionUserById = (id) => {
    return(
        actionPromise('UserById', gql(`query UserById($_id:String) {
        UserFindOne(query: $_id){
          _id, nick, login, avatar {url}
          followers {_id, nick, login},
          following {_id, nick, login}
          } 
        }`,{"_id": JSON.stringify([{ "_id": id }])})
        ))}


export const actionGetPosts = (skip) =>{
    return(
        actionPromise('allPosts', gql(`query allposts($query: String!){
          PostFind(query: $query){
            _id, text, title,
            owner{_id, nick, login, avatar 
             {url}
            }, 
            images{url},
            comments{text},
            createdAt
        }
      }`, {query: JSON.stringify([{},
                {sort:[{_id: -1}],
                    skip:[skip || 0],
                    limit:[500],}
            ])})))
}

export const actionGetAllUsers = (value) =>
    actionPromise('findUsersAll', gql(`query findUsersAll($query:String!) {
                                UserFind(query: $query) {
                                    _id login nick 
                                    avatar { _id url } 
                                }
    }`, {
        query: JSON.stringify([{
            $or: [{ nick: `/${value}/` }, { login: `/${value}/` }]},
            {sort: [{ login: 1 }]},
        ])
    }))

// export const actionUploadPhoto = (file, userId) => async dispatch =>{
//     // let result = await dispatch(actionUploadFile(file))
//     console.log(userId, result._id)
//     dispatch(actionInsertPhoto(result._id, userId))
// }


export const actionPostById = (id) => {
    return(
        actionPromise('PostById', gql(`query PostById($_id:String) {
      PostFind(query: $_id){
        _id createdAt title text,
        images {url},
        owner {login, nick, avatar {url},
        followers {_id, nick, login},
    		following {_id, nick, login}}
      }
	} `, {"_id": JSON.stringify([{ "___owner": id }])}))
    )}

export const actionOnLikePost = (_id) =>
    actionPromise('onLikePost', gql(`mutation LikePost($like:LikeInput){
        LikeUpsert(like:$like){
            _id
        }
    }`, { like: { post: { _id } } }))

export const actionDelLikePost = (_id) =>
    actionPromise('delLikePost', gql(`mutation LikeRemove($like:LikeInput){
            LikeDelete(like:$like){
                _id
            }
        }`, { like: { _id } }))



