/*
 This file is part of GNU Taler
 (C) 2022-2024 Taler Systems S.A.

 GNU Taler 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, or (at your option) any later version.

 GNU Taler 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
 GNU Taler; see the file COPYING.  If not, see <http://www.gnu.org/licenses/>
 */

import {
  Loading,
  urlPattern,
  useCurrentLocation,
  useNavigationContext,
} from "@gnu-taler/web-util/browser";
import { Fragment, VNode, h } from "preact";

import { AccessToken, assertUnreachable } from "@gnu-taler/taler-util";
import { useErrorBoundary } from "preact/hooks";
import { CallengeCompleted } from "./pages/CallengeCompleted.js";
import { Frame } from "./pages/Frame.js";
import { Start } from "./pages/Start.js";

export function Routing(): VNode {
  // check session and defined if this is
  // public routing or private
  return (
    <Frame>
      <PublicRounting />
    </Frame>
  );
}

const publicPages = {
  completed: urlPattern(/\/completed/, () => `#/completed`),
  start: urlPattern(/\/start/, () => `#/start`),
};

function safeGetParam(
  ps: Record<string, string[]>,
  n: string,
): string | undefined {
  if (!ps[n] || ps[n].length == 0) return undefined;
  return ps[n][0];
}

export function safeToURL(s: string | undefined): URL | undefined {
  if (s === undefined) return undefined;
  try {
    return new URL(s);
  } catch (e) {
    return undefined;
  }
}

/**
 * by how the exchange
 * /kyc-spa/KXAFXEWM7E3EJSYD9GJ30FYK1C17AKZWV119ZJA3XGPBBMZFJ2C0
 *
 * @returns
 */
function getAccessTokenFromURL(): AccessToken | undefined {
  if (typeof window === "undefined") return undefined;
  const paths = window.location.pathname.split("/");
  if (paths.length < 3) return undefined;
  return paths[2] as AccessToken;
}

function PublicRounting(): VNode {
  const location = useCurrentLocation(publicPages);
  const { navigateTo } = useNavigationContext();
  useErrorBoundary((e) => {
    console.log("error", e);
  });

  const at = getAccessTokenFromURL();
  if (!at) {
    return <div>no access token</div>;
  }

  switch (location.name) {
    case undefined: {
      navigateTo(publicPages.start.url({}));
      return <Loading />;
    }
    case "start": {
      return (
        <Start
          token={at}
          onLoggedOut={() => {
            navigateTo(publicPages.completed.url({}));
          }}
        />
      );
    }

    case "completed": {
      return <CallengeCompleted />;
    }
    default:
      assertUnreachable(location);
  }
}
