/* global m */
/* eslint-disable no-console */

define(["/socket.io/socket.io.js", "NotebookBackendUsingServer", "HashUtils", "vendor/push", "vendor/mithril"], function(io, NotebookBackendUsingServer, HashUtils, Push, mDiscard) {
    "use strict"

    console.log("NotebookBackendUsingServer", NotebookBackendUsingServer)

    let chatRoom = "test"
    let userID = localStorage.getItem("userID") || "anonymous"
    let chatText = ""
    const messages = []

    let messagesDiv = null

    function startup() {
        chatRoom = HashUtils.getHashParams()["chatRoom"] || chatRoom
        window.onhashchange = () => updateChatRoomFromHash()
        updateHashForChatRoom()
    }

    function updateTitleForChatRoom() {
        const title = document.title.split(" -- ")[0]
        document.title = title + " -- " + chatRoom
    }

    function updateChatRoomFromHash() {
        const hashParams = HashUtils.getHashParams()
        const newChatRoom = hashParams["chatRoom"]
        if (newChatRoom !== chatRoom) {
            chatRoom = newChatRoom
            backend.configure({chatRoom})
            updateTitleForChatRoom()
        }
    }

    function updateHashForChatRoom() {
        const hashParams = HashUtils.getHashParams()
        hashParams["chatRoom"] = chatRoom
        HashUtils.setHashParams(hashParams)
        updateTitleForChatRoom()
    }

    function chatRoomChange(event) {
        chatRoom = event.target.value
        messages.splice(0)
        updateHashForChatRoom()
        backend.configure({chatRoom})
    }

    function userIDChange(event) {
        userID = event.target.value
        backend.configure(undefined, userID)
        localStorage.setItem("userID", userID)
    }

    function chatTextChange(event) {
        chatText = event.target.value
    }

    function sendChatMessage() {
        const timestamp = new Date().toISOString()
        const command = "insert"

        sendMessage({ chatText, userID, timestamp })
        chatText= ""
    }

    function sendMessage(message) {
        backend.addItem(message)
    }

    function textAreaKeyDown(event) {
        console.log("onkeydown", event.keyCode, event)
        if (event.keyCode === 13) {
            chatText = event.target.value
            sendChatMessage()
            return false
        }
        event.redraw = false
        return true
    }

    const TwirlipChat = {
        view: function () {
            return m("div..pa2.overflow-hidden.flex.flex-column.h-100.w-100", [
                m("h4.tc", "Twirlip Chat"),
                m("div.ma1",
                    m("span.dib.tr.w4", "Chat room:"),
                    m("input", {value: chatRoom, onchange: chatRoomChange})
                ),
                m("div.ma1",
                    m("span.dib.tr.w4", "User ID:"),
                    m("input", {value: userID, onchange: userIDChange})
                ),
                m("div.overflow-auto.flex-auto",
                    {
                        oncreate: (vnode) => {
                            messagesDiv = (vnode.dom)
                        },
                    },
                    messages.map(function (message) {
                        var localeTimestamp = new Date(Date.parse(message.timestamp)).toLocaleString()
                        return m("div", [
                            m("span", {title: localeTimestamp, style: "font-size: 50%;"}, message.userID + ":"),
                            " ",
                            message.chatText
                        ])
                    })
                ),
                m("br"),
                m("textarea", {value: chatText, onchange: chatTextChange, onkeydown: textAreaKeyDown}),
                m("button", {onclick: sendChatMessage}, "Send")
            ])
        }
    }

    const responder = {
        onLoaded: () => console.log("onLoaded"),
        addItem: (item, isAlreadyStored) => {
            console.log("addItem", item)
            messages.push(item)
            setTimeout(() => {
                messagesDiv.scrollTop = messagesDiv.scrollHeight
            }, 0)
            if (!document.hasFocus()) {
                Push.create(item.userID + ": " + item.chatText)
            }
        }
    }

    startup()

    const backend = NotebookBackendUsingServer({chatRoom}, userID)

    backend.connect(responder)
    backend.setup(io)

    window.onload = () => m.mount(document.body, TwirlipChat)
})

@@ -133,16 +133,33 @@
 r/push%22,
+ %22vendor/marked%22,
  %22vendor
@@ -227,16 +227,24 @@
 s, Push,
+ marked,
  mDiscar
@@ -2374,32 +2374,115 @@
 urn true%0A    %7D%0A%0A
+    function formatChatMessage(text) %7B%0A        return m.trust(marked(text))%0A    %7D%0A%0A
     const Twirli
@@ -2639,24 +2639,116 @@
 lip Chat%22),%0A
+                m(%22a%22, %7Bhref: %22https://github.github.com/gfm/%22%7D, %22Markdown documentation%22),%0A
             
@@ -3503,16 +3503,20 @@
 n m(%22div
+.pa2
 %22, %5B%0A   
@@ -3598,15 +3598,22 @@
 ze: 
-5
+8
 0%25;%22%7D,
+ m(%22i%22,
  mes
@@ -3627,18 +3627,39 @@
 erID + %22
-:%22
+ @ %22 + localeTimestamp)
 ),%0A     
@@ -3685,41 +3685,40 @@
     
-%22 %22,%0A                            
+m(%22.pl4.pr4%22, formatChatMessage(
 mess
@@ -3729,16 +3729,18 @@
 chatText
+))
 %0A       
@@ -3849,16 +3849,53 @@
  m(%22
-textarea
+div%22,%0A                    m(%22textarea.h4.w-80
 %22, %7B
@@ -3979,24 +3979,28 @@
             
+    
 m(%22button%22, 
@@ -4035,16 +4035,34 @@
 %22Send%22)%0A
+                )%0A
         

Add markdown support to chat and improve textarea sizing