import axios from 'axios'
import { type } from 'os';

onmessage = function (e) {
    const { functionName = "getAccess", access_token = "", messages = [], ai_model = "phi3.5", system_prompt = {role:"system" ,content: "You are a helpful assistant that gives short answers"}} = e.data
    
    let data = {
        ai_model: ai_model,
        messages: messages,
        access_token: access_token
    };

    const getResponse = () => {
        messageComplete:boolean = false
        while(!messageComplete)
        axios.get('https://localhost:5000/interstellar/api/ai_get?access_token=' + access_token)
                .then(Response => {
                    postMessage(Response.data.response)
                    if (Response.data.status == 200) {
                        messageComplete = true
                    }
                }).catch(error => {
                    console.error("Error with GET response request:", error)
                })
    }

    switch (functionName) {
        case "getAccess":
            console.log("getting access...")
            axios.get('https://localhost:5000/interstellar/api/ai_create')
            .then(Response => {
                postMessage(Response.data.access_token)
            }).catch(error => {
                console.error("Error with GET Token request:", error)
            })
            break
        case "postRequest":
            messages.unshift(system_prompt)
            console.log("sending...")
            console.log(messages)
            axios.post('https://localhost:5000/interstellar/api/ai_send', data)
            .then(Response => {
                getResponse()
            }).catch(error => {
                console.error("Error:", error)
            })
            break
    }


}