//
// Copyright 2026 James Pace
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//
// This Source Code Form is "Incompatible With Secondary Licenses", as
// defined by the Mozilla Public License, v. 2.0.
//
import { AppNav, Footer } from "./components/AppNav.tsx";
import { Container, Row, Col, Card } from "react-bootstrap";
import { MediaMtxPlayer } from "./external/MediaMtxPlayer.tsx";
import { atom, useAtomValue } from "jotai";
import { createQueryAtom } from "./utils/query.ts";

const tokenQueryAtom = createQueryAtom("api/mediamtx/login", { retry: true });
const tokenAtom = atom((get) => {
  const response = get(tokenQueryAtom);
  if (response.isPending || response.isError) {
    console.log(response);
    return null;
  }
  return response.data.token;
});

export function Video() {
  const streamName = "image";
  const imageStreamURI =
    "http://" + window.location.hostname + ":8889/" + streamName + "/whep";

  const token = useAtomValue(tokenAtom);

  return (
    <div>
      <AppNav />
      <Container className="vert-padded">
        <Card className="padded">
          <Row>
            <Col lg={8}>
              <MediaMtxPlayer url={imageStreamURI} token={token} />
            </Col>
            <Col lg={4}>Showing stream: "{streamName}".</Col>
          </Row>
        </Card>
      </Container>
      <Footer />
    </div>
  );
}
