import {call, put, select, takeEvery} from "redux-saga/effects";
import {actionPromise, promiseWorker} from "../reducers/promiseReducer";
import {backURL,gql} from "./gql-queries-backurl";
import {actionAboutMe} from "./about-me-actions";

export const actionUploadImage = (file) => {
    let fd = new FormData();
    fd.append("photo", file);
    return actionPromise(
        "uploadFile",
        fetch(backURL+'/upload', {
            method: "POST",
            headers: localStorage.authToken
                ? { Authorization: "Bearer " + localStorage.authToken }
                : {},
            body: fd,
        }).then((res) => res.json())
    );
};



export const actionSetAvatar = (file) =>
    ({type:'SET_AVATAR', file})

export function* setAvatarWorker (action) {
    const {file} = action
    let result = yield call(promiseWorker,actionUploadImage(file));
    let { auth } = yield select();
    let imageId = result._id;
    let userId = auth?.payload?.sub?.id;
    yield call(
        promiseWorker,actionPromise(
            "setAvatar",
            gql(
                `mutation setAva($userId: String, $imageId: ID){
        UserUpsert(user:{_id: $userId, avatar: {_id: $imageId}}){_id}}`,
                { userId: userId, imageId: imageId }
            )
        ));
    yield put(actionAboutMe());
};

export function* setAvatarWatcher() {
    yield takeEvery ('SET_AVATAR',setAvatarWorker)
}


