/*
 * Copyright (C) 2020-2024 by Savoir-faire Linux
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

import React from "react";
import { Route } from "react-router-dom";
import auth from "./auth";
import SignUp from "layouts/SignUp";
import SignIn from "layouts/SignIn";

export const ConfiguredRoute = ({
  component: Component,
  ...rest
}: {
  component: React.ComponentType<any>;
  [key: string]: any;
}) => {
  return (
    <Route
      {...rest}
      render={(props) => {
        if (auth.hasAdmin()) {
          if (auth.isInstalled()) {
            return <Component {...props} />;
          } else if (!auth.isInstalled() && auth.isAuthenticated()) {
            if (auth.uri === "/api/install/ca" || auth.uri === "start") {
              return <SignUp step={1} />;
            } else if (auth.uri === "/api/install/auth") {
              return <SignUp step={2} />;
            } else if (auth.uri === "/api/install/settings") {
              return <SignUp step={3} />;
            } else {
              console.log("Error no matching path for configuration");
            }
          } else {
            return <SignIn />;
          }
        } else {
          return <SignUp step={0} />;
        }
      }}
    />
  );
};
