import FullScreenLoader from "@/components/FullScreenLoader";
import { GlobalFunctions } from "@/GlobalFunctions";
import { RedirectService } from "./RedirectService";
import React from "react";
import { useNavigate, useParams } from "react-router-dom";



export default function Redirect() {

    const navigate = useNavigate();
    let { gsikey } = useParams();

    React.useEffect(() => {
        let error: number = 0;
        sessionStorage.setItem('gsikey', gsikey ?? '0');
        RedirectService.loadTransferArea(parseInt(gsikey ?? '0')).then((response) => {
          //console.log(response);
            error = response.data.errorCode;
            //msg = response.data.errorMessage;
            if(response.data.errorCode == 0){            
                sessionStorage.setItem('TRANSFER_AREA',JSON.stringify(response.data.areTrs));
                sessionStorage.setItem('usuarioLogado',JSON.stringify({
                    token: response.data.jwt.token,
                    refreshToken: response.data.jwt.refreshToken
                }));                
            }
            // else if(error !== 1401){
            //     navigate('/',{replace: true});
            // }
        })
        .catch((_err) => {
            navigate('/404',{replace: true});
        })
        .finally(() => {
            if(error == 0 || error === 1401){
                navigate(`/${GlobalFunctions.getRedirectComponent()}`,{replace: true});                
            }
            // else if(error === 1401){
            //     navigate({pathname: '/',search:`?p=${window.btoa(msg)}`},{replace: true});
            // }
        });
    }, []);   

  return (
  <FullScreenLoader show={true} text="Carregando...Aguarde..." />
  );
}
