import React, { useEffect } from "react";
import { useRenewTokenMutation } from "../generated/graphql";
import { config } from "../config";
import { AuthIFrame, AuthIFrameProps } from "./AuthIFrame";

export interface RenewTokenProps extends AuthIFrameProps {}

export const RenewToken: React.FC<RenewTokenProps> = (props) => {
  const [renewToken, renewTokenResults] = useRenewTokenMutation({
    onError() {},
    onCompleted(data) {
      localStorage.setItem(config.localstorageKeys.token, data.renewToken);
      props.onReady();
    },
  });

  useEffect(() => {
    renewToken();
  }, []);

  if (renewTokenResults.loading) {
    <div>Loading...</div>;
  }
  if (
    renewTokenResults.called &&
    !renewTokenResults.loading &&
    !renewTokenResults.data?.renewToken
  ) {
    return <AuthIFrame {...props} />;
  }
  return null;
};
