import { AxiosResponse } from "axios";
import { useHTTP } from "hooks";
import { pond } from "protobuf-ts/pond";
import { createContext, PropsWithChildren, useContext } from "react";
import { pondURL } from "./pond";

export interface IBackpackAPI {
  addBackpack: (backpack: pond.Backpack) => Promise<any>;
  updateBackpack: (backpackID: number | Long, backpack: pond.Backpack) => Promise<any>;
  removeBackpack: (backpackID: number | Long) => Promise<any>;
  getBackpack: (backpackID: number | Long) => Promise<any>;
  listBackpacks: () => Promise<any>;
}

export const BackpackAPIContext = createContext<IBackpackAPI>({} as IBackpackAPI);

export default function BackpackProvider(props: PropsWithChildren<any>) {
  const { children } = props;
  const { get, post, put, del } = useHTTP();

  const addBackpack = (backpack: pond.Backpack) => {
    const url = pondURL("/backpacks");
    return new Promise<AxiosResponse>((resolve, reject) => {
      post(url, backpack).then(resp => {
        return resolve(resp)
      }).catch(err => {
        return reject(err)
      });
    })
  };

  const updateBackpack = (backpackID: number | Long, backpack: pond.Backpack) => {
    const url = pondURL("/backpacks/" + backpackID);
    return new Promise<AxiosResponse>((resolve, reject) => {
      put(url, backpack).then(resp => {
        return resolve(resp)
      }).catch(err => {
        return reject(err)
      });
    })
  };

  const removeBackpack = (backpackID: number | Long) => {
    const url = pondURL("/backpacks/" + backpackID);
    return new Promise<AxiosResponse>((resolve, reject) => {
      return del(url).then(resp => {
        return resolve(resp)
      }).catch(err => {
        return reject(err)
      });
    })
    
  };

  const getBackpack = (backpackID: number | Long) => {
    const url = pondURL("/backpacks/" + backpackID);
    return new Promise<AxiosResponse>((resolve, reject) => {
      return get(url).then(resp => {
        return resolve(resp)
      }).catch(err => {
        return reject(err)
      });
    })
  };

  const listBackpacks = () => {
    const url = pondURL("/backpacks");
    return new Promise<AxiosResponse>((resolve, reject) => {
      return get(url).then(resp => {
        return resolve(resp)
      }).catch(err => {
        return reject(err)
      });
    })
  };

  return (
    <BackpackAPIContext.Provider
      value={{
        addBackpack,
        updateBackpack,
        removeBackpack,
        getBackpack,
        listBackpacks
      }}>
      {children}
    </BackpackAPIContext.Provider>
  );
}

export const useBackpackAPI = () => useContext(BackpackAPIContext);
