// command/chatWithProgram.ts
import * as vscode from 'vscode';
import { chatWithOpenAIStream ,clearHistory} from './tools';

export async function executeChatWithProgram(context: vscode.ExtensionContext) {
    const panel = vscode.window.createWebviewPanel(
        'chatWithOpenAI',
        'Chat with OpenAI',
        vscode.ViewColumn.One,
        {
            enableScripts: true,
            retainContextWhenHidden: true
        }
    );

    // HTML内容の初期化
    let htmlContent = `
<html>
    <style>
    pre {
        width: 100%; /* 親要素と同じ幅に設定 */
        box-sizing: border-box; /* パディングやボーダーも含めた計算 */
        white-space: pre-wrap; /* 折り返し表示を可能にする */
        overflow-x: auto; /* 必要なら横スクロールバーを表示 */
    }
    </style>        
    <style>
        body {
            display: flex;
            flex-direction: column;
            min-height: 100vh;
            margin: 0;
        }

        #chatLog {
            flex-grow: 1;
        }

        #inputSection {
            background-color: #f3f4f6; /* 背景色を設定 */
            padding: 10px;
            position: sticky;
            bottom: 0;
            width: 100%;
            box-sizing: border-box;
        }
        .inputText {
            text-align: right;
        }
        
        .outputText {
            text-align: left;
        }
    </style>               
    <body>
        <h1>Chat with OpenAI</h1>
        <pre id="chatLog"></pre>
        <div id="inputSection">
            <textarea id="inputMessage" rows="4" cols="50"></textarea><br>
            <button onclick="sendMessage()">Send</button>
            <button onclick="clearHistory()">Clear History</button><br>
        </div>            
        
        <script>
            const vscode = acquireVsCodeApi();
            let currentAiResponseDiv = null;

            function sendMessage() {
                const inputElement = document.getElementById('inputMessage');
                const message = inputElement.value;
                vscode.postMessage({ command: 'message', text: message });
                inputElement.value = '';
                const chatLog = document.getElementById('chatLog');
                chatLog.innerHTML += '<div class="inputText">You: ' + message + '</div><br>';
                    // AIの回答用divを作成
                const aiDiv = document.createElement('div');
                aiDiv.className = 'outputText';
                aiDiv.innerHTML = 'OpenAI: <span class="content"></span>';
                
                chatLog.appendChild(aiDiv);
                contentSpan = aiDiv.querySelector('.content');
                inputElement.value = '';
            }

            function clearHistory() {
                // Clear the chat log on the UI
                document.getElementById('chatLog').textContent = '';

                // Send a message to the extension to clear history in memory
                vscode.postMessage({ command: 'clearHistory' });
            }
                            
            window.addEventListener('message', event => {
                if (event.data.command === 'receiveChunk') {
                    // 受信したデータを span.content に追記
                    contentSpan.textContent += event.data.text;
                } else if (event.data.command === 'error') {
                    contentSpan.textContent += event.data.text;
                }
            });
        </script>
    </body>
</html>`;

    panel.webview.html = htmlContent;

    // メッセージのリスナーを設定
    context.subscriptions.push(
        panel.webview.onDidReceiveMessage(async message => {
            if (message.command === 'message') {
                try {
                    const stream = chatWithOpenAIStream(message.text);
                    
                    for await (const chunk of stream) {
                        panel.webview.postMessage({
                            command: 'receiveChunk',
                            text: chunk
                        });
                    }

                } catch (error) {
                    console.error("Error in executeChatWithProgram:", error);
                    panel.webview.postMessage({
                        command: 'error',
                        text: error instanceof Error ? error.message : "An error occurred while chatting with OpenAI."
                    });
                }
            } else if (message.command === 'clearHistory') {
                clearHistory();
            }            
        }, undefined, context.subscriptions)
    );
}
