import { APIEndPoint, PartyStatus, SelfStatus, UpdatableSelfStatus } from "./PartyContext";

export const parseURI = (uri: string): APIEndPoint | undefined => {
    // const x = uri.match(/https?:\/\/(?<partyName>.+)\.party\.leafbla\.de\/(?<token>.+)/);
    const x = uri.match(/https?:\/\/[^/]+\/(?<token>.+)/);
    if (x === null || x.groups === undefined) return;
    // const partyName = x.groups["partyName"];
    const partyName = "xmas";
    const token = x.groups["token"];
    if (!partyName || !token) return;
    return { partyName, token };
};

const apiUrl = (apiEndPoint : APIEndPoint): string => {

    let a =  `https://party.leafbla.de/api/${apiEndPoint.partyName}/${apiEndPoint.token}`;
    console.log(a);
    return a;
};

export const getSelfStatusRequest = async (apiEndpoint: APIEndPoint): Promise<SelfStatus> => {
    const result = await fetch(`${apiUrl(apiEndpoint)}/me`);
    if (!result.ok) throw new Error("Error sending getSelfRequest");
    const data = await result.json();
    return data as SelfStatus;
};

export const getPartyStatusRequest = async (apiEndpoint: APIEndPoint): Promise<PartyStatus> => {
    const result = await fetch(`${apiUrl(apiEndpoint)}/status`);
    if (!result.ok) throw new Error("Error sending getPartyRequest");
    const data = await result.json();
    return data as PartyStatus;
};

export const modifySelfRequest = async (apiEndpoint: APIEndPoint, payload: UpdatableSelfStatus): Promise<SelfStatus> => {
    const result = await fetch(`${apiUrl(apiEndpoint)}/me`, { method: "PATCH", body: JSON.stringify(payload), headers: { "Content-Type": "application/json" } });
    if (!result.ok) throw new Error("Error sending modifySelfRequest");
    const data = await result.json();
    return data as SelfStatus;
};
