Code viewer for World: New World
// Cloned by Aarekh Rana on 22 Nov 2023 from World "Chat with GPT model" by Starter user 
// Please leave this clone trail here.

const threeScript = document.createElement('script');
    threeScript.src = 'https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js';
    document.head.appendChild(threeScript);

// talk to OpenAI GPT model (ChatGPT)
// adapted from: https://platform.openai.com/docs/api-reference/making-requests
const openaiURL = "https://api.openai.com/v1/chat/completions"; // can POST to this 3rd party URL
const themodel = "gpt-3.5-turbo"; // the OpenAI model we are going to talk to 

// default API key and prompt:
var apikey = "";
var theprompt = "hello";

// default body is margin 0 and padding 0 
// give it more whitespace:
$('body').css("margin", "20px");
$('body').css("padding", "20px");

document.write(`
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f4;
            margin: 0;
            padding: 20px;
        }
        .container {
            max-width: 600px;
            margin: 0 auto;
            padding: 20px;
            background-color: white;
            border-radius: 10px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }
        .header {
            text-align: center;
            color: #333;
            <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
        }
        .api-key-section, .chat-section, .response-section, .drawing-section {
            margin-bottom: 20px;
        }
        input[type="text"], input[type="password"] {
            width: calc(100% - 22px);
            padding: 10px;
            margin-bottom: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
        }
        button {
            width: 100%;
            padding: 10px;
            border: none;
            border-radius: 5px;
            background-color: #007bff;
            color: white;
            cursor: pointer;
        }
        button.clear-btn {
            background-color: #dc3545;
        }
        .response-section, .drawing-section {
            background-color: #e9ecef;
            padding: 15px;
            border-radius: 5px;
        }
    </style>

    <div class="container">
        <h1 class="header">Chat with GPT Model</h1>

        <div class="api-key-section">
    <h3>Enter API Key</h3>
    <input type="password" id="apikey" placeholder="Enter your API key">
    <button onclick="setkey();" class="set-api-btn">Set API Key</button>
    <div id="enterkey"></div> <!-- Placeholder for API key set message -->
        </div>
    

        <div class="chat-section">
            <h3>Enter a Prompt</h3>
            <input type="text" id="me" placeholder="Type your prompt here">
            <button onclick="sendchat();" class="send-btn">Send</button>
        </div>

        <div class="response-section">
            <h3>GPT Replies</h3>
            <div id="them"></div>
        </div>

        <button onclick="clearScreen();" class="clear-btn">Clear Screen</button>

        <div class="drawing-section" id="drawing-section">
            <h3>Drawing Section</h3>
            <!-- Add your drawing elements here -->
        </div>
    </div>
`);

// const openaiURL = "https://api.openai.com/v1/chat/completions";
// const themodel = "gpt-3.5-turbo";
// var apikey = "";

function setkey() {
    apikey = document.getElementById("apikey").value.trim();
    // Display "API key set!" message
    alert("API key has been set!");
    // Check if the message element exists, if not create and append it
    var enterKeyElement = document.getElementById("enterkey");
    if (!enterKeyElement) {
        enterKeyElement = document.createElement("div");
        enterKeyElement.id = "enterkey";
        document.getElementsByClassName("api-key-section")[0].appendChild(enterKeyElement);
    }
    enterKeyElement.innerHTML = "<b>API key set!</b>";
}


document.getElementById('me').addEventListener('keydown', function (event) {
    if (event.keyCode === 13) {
        sendchat();
    }
});

function sendchat() {
    var theprompt = document.getElementById("me").value;

    var thedata = {
        "model": themodel,
        "temperature": 0.7,
        "messages": [{"role": "user", "content": theprompt}]
    };

    var xhr = new XMLHttpRequest();
    xhr.open("POST", openaiURL);
    xhr.setRequestHeader("Content-Type", "application/json");
    xhr.setRequestHeader("Authorization", "Bearer " + apikey);
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                var data = JSON.parse(xhr.responseText);
                successfn(data);
            } else {
                errorfn();
            }
        }
    };
    xhr.send(JSON.stringify(thedata));
}

// function successfn(data) {
//     var answer = data.choices[0].message.content;
//     document.getElementById("them").innerHTML += "<p>" + answer + "</p>";
//     document.getElementById("me").value = ""; // Clear the prompt input field
// }

// function successfn(data) {
//     var answer = data.choices[0].message.content;
//     document.getElementById("them").innerHTML += "<p>" + answer + "</p>";
//     // Don't clear the prompt input field
//     // document.getElementById("me").value = "";
// }

function successfn(data) {
    var answer = data.choices[0].message.content;

    // Extracting the JavaScript part from the answer
    var scriptStart = answer.indexOf('<script>') + '<script>'.length;
    var scriptEnd = answer.indexOf('</script>');
    var scriptContent = answer.substring(scriptStart, scriptEnd).trim();

    try {
        eval(scriptContent);
    } catch (error) {
        console.error("Error executing received code:", error);
    }
}

// function runReceivedCode(code) {
//     // Implement the logic to run the received code and display the result in the drawing section
//     // For security reasons, you should sanitize and validate the code before executing it

//     try {
//         // Create a script element and append the code to it
//         var script = document.createElement('script');
//         script.textContent = code;

//         // Append the script to the drawing section
//         document.getElementById("drawing-section").appendChild(script);
//     } catch (error) {
//         console.error("Error executing received code:", error);
//     }
// }

function runReceivedCode(code) {
    try {
        // Log the code for debugging purposes
        console.log("Executing code:", code);

        // Use eval to execute the code
        eval(code);

    } catch (error) {
        console.error("Error executing received code:", error);
    }
}



function errorfn() {
    if (apikey === "") {
        alert("Enter API key to be able to chat.");
    } else {
        alert("Unknown error occurred.");
    }
}

function clearScreen() {
    document.getElementById("them").innerHTML = "";
    document.getElementById("drawing-section").innerHTML = ""; // Clear the drawing section
}