<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
        <meta name="description" content="" />
        <meta name="author" content="" />
        <title>{{title_variable}}</title>
        <link rel="icon" type="image/x-icon" href="{{ url_for('static', filename='dist/assets/favicon.ico') }}" />
        <!-- Font Awesome icons (free version)-->
        <script src="https://use.fontawesome.com/releases/v5.15.3/js/all.js" crossorigin="anonymous"></script>
        <!-- Google fonts-->
        <link href="https://fonts.googleapis.com/css?family=Varela+Round" rel="stylesheet" />
        <link href="https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i" rel="stylesheet" />
        <!-- Core theme CSS (includes Bootstrap)-->
        <!-- <link href="{{ url_for('static', filename='dist/css/styles.css') }}" rel="stylesheet" /> -->
        <script src="https://cdn.tailwindcss.com"></script>
        <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.js"></script>
        <script src="/static/utils/vue-spinner.js"></script>
        <script>
          var PulseLoader = VueSpinner.PulseLoader
        </script>
        <script>
            function pressed(e) {
                // Has the enter key been pressed?
                if ( (window.event ? event.keyCode : e.which) == 13) { 
                    // If it has been so, manually submit the <form>
                    document.forms[0].submit();
                    
                }
            }

        </script>

    </head>
    <body id="page-top" >

        <div id="app" class="flex flex-col  h-screen w-screen overflow-y-auto" style="background-image: url('/static/assets/background.png')">
            <!-- Header -->
            <div class="h-[10%]sticky top-0 z-40 w-auto backdrop-blur flex-none transition-colors duration-500 lg:z-50  supports-backdrop-blur:bg-white/60">
                <div class="max-w-8xl mx-auto">
                    <div class=" border-2 border-slate-400/10 lg:border-0 mx-4 lg:mx-0">
                        <div class="relative flex items-center">
                            <a class="mt-2 mx-2 flex overflow-hidden md:w-auto items-center" href="/">
                                <img class="h-8 w-40 logo" src="/static/assets/logo.png">
                            </a>
                            <button class="bg-blue-200 my-3 rounded-lg px-1" v-on:click="reset" > Reset</button>
                            <div class="relative hidden lg:flex items-center ml-auto ">
                                <nav class="text-base leading-6 font-semibold text-slate-700 items-center">
                                </nav>
                            </div>
                        </div>
                    </div>
  
                </div>
            </div>
            <!-- Main Chat -->
            <div class="flex flex-col chat-box w-full h-[90%]">
                
                <div class="flex flex-col box-border h-[10%] w-100% justify-center items-center">
                    <h1 class="text-lg">Welcome to your own Chatbot</h1>
                </div>
                <!-- ChatWindow -->
                <div class="h-[70%] overflow-y-scroll overflow-x-hidden px-10 py-3 " id="chatWindow">
                    <ul class="flex-auto  font-sans text-base">
                        <div v-for="item in conversation" :key="item.type">
                            <li v-if="item.type==1" class="relative min-h-[68px] text-right">
                              <div class="whitespace-normal px-5 bg-blue-300 bg-opacity-50 inline-block align-top rounded-lg break-all mt-2" >[[item.content]]</div>
                            </li>
                            <li v-else-if="item.type===2 " class="relative min-h-[68px] text-left">
                              <div class="whitespace-pre-line px-5 bg-gray-300 inline-block bg-opacity-75 rounded-lg ">[[item.content]]</div>
                            </li>
                          </div>
                        <!-- loading -->
                        <div v-show="this.isLoading == true" class="flex bg-gray-300 text-left w-16 items-center justify-center rounded-lg pt-1 mt-2">
                            <pulse-loader></pulse-loader>
                        </div>
                    </ul>
                </div>

                <div class="h-[20%] border-black px-10 py-5  bottom-0">
                    <div class="flex px-3 py-2 rounded-lg border-black ">
                      <textarea class="flex resize-none w-full border-2 border-gray-400 mx-2 my-2 rounded-lg" 
                                placeholder="Hi, you can ask me anything here to chat with me~" @keypress.enter.prevent="query"  @keydown.enter.shift.exact.prevent="user_input += '\n'"
                                v-model="user_input"></textarea>
                      <button class="bg-blue-200 my-3 rounded-lg px-1" v-on:click="query">chat</button>
                    </div>
                </div>
                
            </div>


        </div>

    </body>
    <script>
        const { createApp } = Vue
    
        createApp({
        data() {
            return {
                user_input: "",
                conversation: [
                        {
                            type: 2,
                            name: 'Your Assistant',
                            content: 'Welcome to chat with me !',
                        }
                    ],
                isLoading: false
            }
        },
        components: {
             PulseLoader
        },
        delimiters: ['[[', ']]'],
        methods:{
            query() {
                if(this.user_input == "") {
                    alert("Your input is empty")
                    return 0
                }
                this.isLoading = true
                this.conversation.push({
                type:1,
                name: 'User',
                content: this.user_input
                })
                // axios.post('/predict', 
                //             {'History': this.conversation, 'Input' : this.user_input})
                //             .then(response => {
                //                 console.log(response.data)
                //                 this.conversation.push({
                //                 type:2,
                //                 name: 'Your Assistant',
                //                 content: response.data,
                //                 })
                //                 this.isLoading = false
                //                 this.user_input = ""
                // })
                fetch('/predict',
                    {method:"POST",
                        headers: {
                            "Content-Type": "application/json",
                        },
                        body: JSON.stringify({'History': this.conversation, 'Input' : this.user_input}),
                    }) 
                .then(response => { 

                    this.conversation.push({
                        type:2,
                        name: 'Your Assistant',
                        content: "",
                        vote:0
                    })
                    const reader = response.body.getReader() 
                    const decoder = new TextDecoder()

                    const read = () => { 
                        reader.read().then(res => {
                            const chunk = decoder.decode(res.value || new Uint8Array(), {stream: !res.done}) 
                            let conv_len = this.conversation.length
                            if(chunk != ""){
                                this.conversation[conv_len - 1]["content"] =  chunk
                            }
                            // console.log(this.conversation)
                            // console.log(chunk) // do something with the chunk of data received 
                            this.isLoading = false

                            if(!res.done) read() 
                        })
                    }
                    read() 
                    this.user_input = ""
                }) 
                .catch(error => console.error(error)) 

                
            },
            reset(){
                this.conversation = [
                {
                    type: 2,
                    name: 'Your Assistant',
                    content: 'Welcome to chat with me !',
                }
            ]
            }
        },
        updated(){
          let ele = document.getElementById('chatWindow');
          ele.scrollTop = ele.scrollHeight;
        }

        }).mount('#app')
    </script>
</html>