import {call, put, select, takeEvery} from "redux-saga/effects";
import {actionPromise, promiseWorker} from "../reducers/promiseReducer";
import {backURL, gql} from "./index";
import {actionAboutMe} from "./index";
import {actionPlaylistFindByOwner} from "./index";


export const actionCreatePlaylist = (name) =>
    ({type:'CREATE_PLAYLIST', name})

export function* createPlaylistWorker (action) {
    let {name} = action
    yield call(promiseWorker,actionPromise('createPlaylist', gql(`mutation p($playlist:PlaylistInput) {
         PlaylistUpsert(playlist:$playlist) {
         _id 
         }
      }`, {playlist: {name}})))
    yield put (actionPlaylistFindByOwner())
}


export function* createPlaylistWatcher() {
    yield takeEvery ('CREATE_PLAYLIST',createPlaylistWorker)
}


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


export const actionFullUploadPlaylists = (array=[]) =>
    ({type:'FULL_UPLOAD', array})



export function* fullUploadPlaylistsWorker (action) {
    const {array} = action
    console.log(array,'eeeeeeeee')
    let { route } = yield select()
    let playlistId = route.params?._id;
    let arr = []
    for (let i=0; i<array.length; i++) {
        if ('_id' in array[i]) {
            arr.push({_id:array[i]._id})
        }else {
            let result = yield call(promiseWorker,actionUploadTrackToPlaylist(array[i]));
            let trackId = result?._id
            arr.push({_id: trackId})
        }

    }
    yield put(actionSetTrackToPlaylist(playlistId, arr))
    yield put(actionAboutMe())
}


export function* fullUploadPlaylistsWatcher () {
    yield takeEvery ('FULL_UPLOAD',fullUploadPlaylistsWorker)
}


export const actionSetTrackToPlaylist = (playlistId,arr) =>
    ({type:'SET_TRACK_TO_PLAYLIST', playlistId,arr})


export function* setTrackToPlaylistWorker (action) {
    const {playlistId,arr} = action
    yield call(
        promiseWorker,actionPromise('createPlaylist', gql(`mutation p($playlist:PlaylistInput) {
         PlaylistUpsert(playlist:$playlist) {
         _id 
         }
      }`, {playlist: {_id: playlistId,tracks: arr}}))
    );
    console.log(playlistId,arr,'4topolu4')
    yield put (actionPlaylistById(playlistId))
    yield put(actionAboutMe());
};


export function* setTrackToPlaylistWatcher() {
    yield takeEvery ('SET_TRACK_TO_PLAYLIST', setTrackToPlaylistWorker)
}





export const actionPlaylistById = (_id) =>
    ({type:'PLAYLIST_BY_ID', _id})

export function* playlistByIdWorker (action) {
    let {_id} = action
    yield call(promiseWorker,actionPromise('playlistById', gql(`query playlistById($q: String){
    PlaylistFindOne(query: $q){
        _id name owner {login} tracks {_id url originalFileName}
    }
}`, { q: JSON.stringify([{ _id: _id}]) } )))
}


export function* playlistByIdWatcher() {
    yield takeEvery ('PLAYLIST_BY_ID',playlistByIdWorker)
}

