"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useStreamKey = void 0;
// Just to be 100% sure it's imported successfully
require("../crypto-polyfill");
const crypto_1 = require("@atproto/crypto");
const react_1 = require("react");
const react_native_1 = require("react-native");
const accounts_1 = require("viem/accounts");
const browser_1 = require("../lib/browser");
const xrpc_1 = require("../streamplace-store/xrpc");
const livestream_store_1 = require("./livestream-store");
const useStreamKey = () => {
    const pdsAgent = (0, xrpc_1.usePDSAgent)();
    const streamKey = (0, livestream_store_1.useLivestreamStore)((state) => state.streamKey);
    const setStreamKey = (0, livestream_store_1.useLivestreamStore)((state) => state.setStreamKey);
    const [key, setKey] = (0, react_1.useState)(streamKey ? JSON.parse(streamKey) : null);
    const [error, setError] = (0, react_1.useState)(null);
    (0, react_1.useEffect)(() => {
        if (key)
            return; // already have key
        const generateKey = async () => {
            if (!pdsAgent) {
                setError("PDS Agent is not available");
                return;
            }
            let did = pdsAgent.did;
            if (!did) {
                setError("PDS Agent did is not available (not logged in?)");
                return;
            }
            const keypair = await crypto_1.Secp256k1Keypair.create({ exportable: true });
            const exportedKey = await keypair.export();
            const didBytes = new TextEncoder().encode(did);
            const combinedKey = new Uint8Array([...exportedKey, ...didBytes]);
            const multibaseKey = (0, crypto_1.bytesToMultibase)(combinedKey, "base58btc");
            const hexKey = Array.from(exportedKey)
                .map((b) => b.toString(16).padStart(2, "0"))
                .join("");
            const account = (0, accounts_1.privateKeyToAccount)(`0x${hexKey}`);
            const newKey = {
                privateKey: multibaseKey,
                did: keypair.did(),
                address: account.address.toLowerCase(),
            };
            let platform = react_native_1.Platform.OS;
            if (react_native_1.Platform.OS === "web" &&
                typeof window !== "undefined" &&
                window.navigator) {
                if (window.navigator.userAgent.includes("streamplace-desktop")) {
                    platform = "Desktop";
                }
                else {
                    platform = (0, browser_1.getBrowserName)(window.navigator.userAgent);
                    if (platform !== "unknown") {
                        platform = platform;
                    }
                }
            }
            else if (platform === "android") {
                platform = "Android";
            }
            else if (platform === "ios") {
                platform = "iOS";
            }
            else if (platform === "macos") {
                platform = "macOS";
            }
            else if (platform === "windows") {
                platform = "Windows";
            }
            const record = {
                $type: "place.stream.key",
                signingKey: keypair.did(),
                createdAt: new Date().toISOString(),
                createdBy: "Streamplace on " + platform,
            };
            await pdsAgent.com.atproto.repo.createRecord({
                repo: did,
                collection: "place.stream.key",
                record,
            });
            setStreamKey(JSON.stringify(newKey));
            setKey(newKey);
        };
        generateKey().catch((err) => setError(err.message));
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [key, setStreamKey]);
    return { streamKey: key, error };
};
exports.useStreamKey = useStreamKey;
//# sourceMappingURL=stream-key.js.map