import * as apiTodo from "./api/Todo";
import * as apiEntry from "./api/Entry";
import * as apiAuth from "./api/Auth";

export function fetchTodos(){
    return (dispatch,getState) => {
      dispatch({ type: "FETCH_TODOS_STARTED" });
      return apiTodo
        .getTodos(getState().auth.token.jwt)
        .then((todos ) => {
          dispatch({ type: "FETCH_TODOS_SUCCEEDED", todos });
        })
        .catch((error) =>  {
          dispatch({ type: "FETCH_TODOS_FAILED", error })
        }
        );
    };
  }

  export function getTodoById(id){
    return (getState) => {
      apiTodo.getTodoById(id,getState().auth.token.jwt);
    };
  }

export function updateTodo(id, name){
  return (dispatch,getState) => {
    apiTodo.updateTodo(id, name,getState().auth.token.jwt).then(() => {
      dispatch(fetchTodos(getState().auth.token.jwt));
    });
  };
}

export function addTodo(name){
  return (dispatch,getState) => {
    apiTodo.addTodo(name,getState().auth.token.jwt).then(() => {
      dispatch(fetchTodos(getState().auth.token.jwt));
    });
  };
}

export function deleteTodo(id){
  return (dispatch,getState) => {
    apiTodo.deleteTodo(id,getState().auth.token.jwt).then(() => {
      dispatch(fetchTodos(getState().auth.token.jwt));
    });
  };
}

export function fetchEntries(todoListId){
  return (dispatch,getState) => {
    dispatch({ type: "FETCH_ENTRIES_STARTED" });

    return apiEntry
      .getEntriesByTodoListId(todoListId,getState().auth.token.jwt)
      .then((entries) => {
        dispatch({ type: "FETCH_ENTRIES_SUCCEEDED", entries });
      })
      .catch((error) =>  {
        dispatch({ type: "FETCH_ENTRIES_FAILED", error })
      }
      );
  };
}

export function updateEntry(id, title, todoListId){
  return (dispatch,getState) => {
    apiEntry.updateEntry(id, title,getState().auth.token.jwt).then(() => {
      dispatch(fetchEntries(todoListId,getState().auth.token.jwt));
    });
  };
}

export function addEntry(todoListId,title,done){
  return (dispatch,getState) => {
    apiEntry.addEntryToTodo(todoListId,title,done,getState().auth.token.jwt).then(() => {
      dispatch(fetchEntries(todoListId,getState().auth.token.jwt));
    });
  };
}

export function deleteEntry(id,todoListId){
  return (dispatch,getState) => {
    apiEntry.deleteEntry(id,getState().auth.token.jwt).then(() => {
      dispatch(fetchEntries(todoListId,getState().auth.token.jwt));
    });
  };
}

export function login(username, password){
  return (dispatch) => {
    dispatch({ type: "LOGIN_STARTED" });

    return apiAuth
    .signin(username, password)
    .then((token ) => {
      dispatch({ type: "LOGIN_SUCCEEDED", token });
    })
    .catch((error) =>  {
      dispatch({ type: "LOGIN_FAILED", error })
    }
    );
  };
}
