export const serverRequest = async (requestData) => {
    let res = {
        success: true,
        message: "",
        data: undefined
    };
    let accessToken = requestData.accessToken;
    if (accessToken?.length == 0 && (!requestData.routeType || requestData.routeType == "private")) {
        res.success = false;
        res.message = "Access Token Missing";
    }
    else {
        //console.log("request data",requestData)
        let fetchObj = {
            headers: {
                "Authorization": "Bearer " + accessToken,
                ...(requestData.headers ?? {})
            },
            method: requestData.reqType,
            body: !requestData.preventStringify ? JSON.stringify({ ...requestData.body }) : requestData.body
        };
        requestData.routeType == "public" ? delete fetchObj.headers : null;
        !requestData.body ? delete fetchObj.body : null;
        let serverRes = await fetch(requestData.url, fetchObj);
        let data = requestData.responseType == "JSON" || requestData.responseType == undefined ? await serverRes.json() : { success: true, message: "", data: await serverRes.blob() };
        res = { ...data };
    }
    return res;
};
export const getAccessTokenFromStore = async () => localStorage.getItem("Token");
export const chunksExtractor = (inputStream, partialChunk) => {
    //console.log("Stream Data",inputStream,partialChunk);
    let stream = (partialChunk ? partialChunk.data : "") + inputStream;
    let indexes = getChunkIndexes(stream);
    let chunks = [];
    let partialChunkIndex = (indexes.start.length > indexes.end.length) ? indexes.start.pop() : -1; //partial/malformed ending
    (indexes.start.length < indexes.end.length && !partialChunk) ? indexes.end.shift() : -1; //invalid start
    //console.log("indexes after",indexes);
    indexes.start.forEach((index, i) => {
        let word = stream.substring(index, indexes.end[i] + 1);
        try {
            let chunk = JSON.parse(word);
            chunks.push(chunk);
        }
        catch (e) {
            //console.log("Stream Recieved",e);
        }
    });
    (partialChunkIndex != -1) ? chunks.push({
        id: "partial-chunk",
        messageId: null,
        conversationId: null,
        responseType: "chunk",
        data: stream.substring(partialChunkIndex, stream.length + 1)
    }) : null;
    return chunks;
};
const getChunkIndexes = (stream) => {
    let endIndexes = [];
    let startIndexes = [0];
    let openBracketCount = 0;
    for (let i = 0; i < stream.length; i++) {
        let ch = stream[i];
        if (ch == "{") {
            openBracketCount++;
        }
        if (ch == "}") {
            openBracketCount--;
        }
        if (openBracketCount == 0) {
            endIndexes.push(i);
            if (i < stream.length - 1) {
                startIndexes.push(i + 1);
            }
        }
    }
    ;
    return {
        start: startIndexes,
        end: endIndexes
    };
};
export function objectToQueryParams(obj) {
    return new URLSearchParams(obj).toString();
}
export const getLocation = async () => {
    let res = {
        success: true,
        message: "",
        data: undefined
    };
    let serRes = await fetch("https://ipapi.co/json/");
    let data = res ? await serRes.json() : null;
    res.data = data;
    return res;
    //     .then((response) => response.json())
    //     .then((data) => {
    //         res.data=data
    //         return res
    //         // console.log("City:", data.city);
    //         // console.log("Region:", data.region);
    //         // console.log("Country:", data.country);
    //         // console.log("Latitude:", data.latitude);
    //         // console.log("Longitude:", data.longitude);
    // }).catch((error) =>{
    //     res.success=false;
    //     res.message=error
    //     return res;
    // });
    // navigator.geolocation.getCurrentPosition(
    //     (position) => {
    //         res.data=position;
    //         return res;
    //     },
    //     (err) => {
    //         res.success=false;
    //         res.message=err.message;
    //         return res;
    //     }
    //);
};
const getLayout = () => {
    let layout = "web";
    if (window.innerWidth <= 500) {
        layout = "mobile";
    }
    if (window.innerWidth > 500 && window.innerWidth <= 1024) {
        layout = "tab";
    }
    if (window.innerWidth > 1024 && window.innerWidth <= 1920) {
        layout = "laptop";
    }
    if (window.innerWidth > 1920) {
        layout = "pc";
    }
    return layout;
};
export const preSanitizeContent = (conversation) => {
    let wrapperIndexs = { start: conversation.indexOf("$followupquestions$"), end: conversation.indexOf("$/followupquestions$") };
    return ({
        conversation: conversation.substring(0, wrapperIndexs.start != -1 ? wrapperIndexs.start : conversation.length).replace("DATAPOINT_NEXUS", ""), //,formatText(),
        followupQuestions: getFollowupQuestions(conversation.substring(wrapperIndexs.start, conversation.length))
    });
};
export const getFollowupQuestions = (conversation) => {
    //$followupquestions$
    //$fq$What programs or degrees does CBU offer?$/fq$
    //$fq$Can you tell me about student life at CBU?$/fq$
    //$fq$What are the housing options available for students?$/fq$
    //$/followupquestions$
    let wrapperIndexs = { start: conversation.indexOf("$followupquestions$"), end: conversation.length - 1 };
    let wrapperTagLength = "$followupquestions$".length;
    let itemTagLength = "$fq$".length;
    let questionsUnbaked = (wrapperIndexs.start != -1 && wrapperIndexs.end != -1) ? conversation.substring(wrapperIndexs.start + wrapperTagLength, wrapperIndexs.end) : undefined;
    let questionsIndexes = {
        start: questionsUnbaked ? [...questionsUnbaked.matchAll(/\$fq\$/g)].map((item) => item.index) : [],
        end: questionsUnbaked ? [...questionsUnbaked.matchAll(/\$\/fq\$/g)].map((item) => item.index) : []
    };
    //console.log("Baked String",questionsIndexes)
    let questionsExtracted = questionsIndexes.start.map((element, i) => {
        if (element != undefined && questionsUnbaked && questionsIndexes.end && questionsIndexes.end[i] != undefined) {
            return questionsUnbaked?.substring(element + itemTagLength, questionsIndexes.end[i]).replaceAll(/\n/g, "").trim();
        }
    });
    return questionsExtracted;
};
export const formatText = (conversation) => {
    let paragraphWrapperIndexs = { start: conversation.indexOf("$paragraph$"), end: conversation.length - 1 };
    let bodyWrapperIndexs = { start: paragraphWrapperIndexs.start != -1 ? paragraphWrapperIndexs.start : conversation.length, end: conversation.lastIndexOf("$/paragraph$") != -1 ? conversation.lastIndexOf("$/paragraph$") : conversation.length - 1 };
    let itemTagLength = "$paragraph$".length;
    let footerWrapperIndexs = { start: bodyWrapperIndexs.end + itemTagLength + 1, end: conversation.length - 1 };
    let header = conversation.substring(0, paragraphWrapperIndexs.start != -1 ? paragraphWrapperIndexs.start : conversation.length);
    let body = conversation.substring(bodyWrapperIndexs.start, bodyWrapperIndexs.end + 1);
    let footer = conversation.substring(footerWrapperIndexs.start, footerWrapperIndexs.end + 1);
    let paragraphIndexes = {
        start: body ? [...body.matchAll(/\$paragraph\$/g)].map((item) => item.index) : [],
        end: body ? [...body.matchAll(/\$\/paragraph\$/g)].map((item) => item.index) : []
    };
    let paragraphExtracted = paragraphIndexes.start.map((element, i) => {
        if (element != undefined) {
            return body?.substring(element + itemTagLength, paragraphIndexes.end[i] != undefined ? paragraphIndexes.end[i] : conversation.length).replaceAll(/\n/g, "").trim();
        }
    });
    return ({
        header: header,
        body: paragraphExtracted,
        footer: footer
    });
};
export const toRgba = (color, alpha) => {
    if (!color)
        throw new Error("Invalid color input");
    if (color.startsWith("#")) {
        let hex = color.replace(/^#/, "");
        let r, g, b;
        if (hex.length === 3) {
            r = parseInt(hex[0] + hex[0], 16);
            g = parseInt(hex[1] + hex[1], 16);
            b = parseInt(hex[2] + hex[2], 16);
        }
        else if (hex.length === 6) {
            r = parseInt(hex.slice(0, 2), 16);
            g = parseInt(hex.slice(2, 4), 16);
            b = parseInt(hex.slice(4, 6), 16);
        }
        else {
            throw new Error("Invalid HEX color.");
        }
        //console.log("To RGBA",`rgba(${r}, ${g}, ${b}, ${alpha})`)
        return `rgba(${r}, ${g}, ${b}, ${alpha})`;
    }
    const rgbMatch = color.match(/^rgb(a?)\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)$/);
    if (rgbMatch) {
        const [, , r, g, b, existingAlpha] = rgbMatch;
        //console.log("To RGBA",`rgba(${r}, ${g}, ${b}, ${existingAlpha !== undefined ? existingAlpha : alpha})`);
        return `rgba(${r}, ${g}, ${b}, ${existingAlpha !== undefined ? existingAlpha : alpha})`;
    }
    //console.log("Invalid color",color,alpha);
    throw new Error("Invalid color format. Use HEX, RGB, or RGBA.");
};
export const getPointingVector = (origin, point, scale) => {
    let transformedPoint = { x: point.x - origin.x, y: origin.y - point.y };
    let magnitude = Math.sqrt(Math.pow(transformedPoint.x, 2) + Math.pow(transformedPoint.y, 2));
    let normalised = { x: (scale * transformedPoint.x) / magnitude, y: (scale * transformedPoint.y) / magnitude };
    return normalised;
};
// const bakeRequest=(data:AgentAction)=>{
//     switch(data.workingData?.method){
//         case "POST":
//             break;
//     }
// }
//# sourceMappingURL=utils.js.map