import "../../components/LoadingCircle.js"

class ForumPanel extends Shadow {
    forums = [
        "HY"
    ]
    messages = []

    render() {
        VStack(() => {
            if(this.messages.length > 0) {

                let previousDate = null

                for(let i=0; i<this.messages.length; i++) {
                    let message = this.messages[i]
                    const dateParts = this.parseDate(message.time);
                    const { date, time } = dateParts;

                    if (previousDate !== date) {
                        previousDate = date;

                        p(date)
                            .textAlign("center")
                            .opacity(0.5)
                            .marginVertical(1, em)
                            .color("var(--divider)")
                    }

                    VStack(() => {
                        HStack(() => {
                            p(message.sentBy)
                                .fontWeight("bold")
                                .marginBottom(0.3, em)

                            p(util.formatTime(message.time))
                                .opacity(0.2)
                                .marginLeft(1, em)
                        })
                        p(message.text)
                    })
                }
            } else {
                LoadingCircle()
            }
        })
        .gap(1, em)
        .position("relative")
        .overflow("scroll")
        .height(100, pct)
        .width(96, pct)
        .paddingTop(5, em)
        .paddingBottom(2, em)
        .paddingLeft(4, pct)
        .backgroundColor("var(--darkbrown)")
        .onAppear(async () => {
            console.log("appear")
            requestAnimationFrame(() => {
                this.scrollTop = this.scrollHeight
            });
            let res = await Socket.send({app: "FORUM", operation: "GET", msg: {forum: "HY", number: 100}})
            if(!res) console.error("failed to get messages")
            if(res.msg.length > 0 && this.messages.length === 0) {
                console.log("rerendering", res.msg)
                this.messages = res.msg
                this.rerender()
            }
            window.addEventListener("new-post", (e) => {
                this.messages = e.detail
                if(e.detail.length !== this.messages || e.detail.last.time !== this.messages.last.time || e.detail.first.time !== this.messages.first.time) {
                    this.rerender()
                }
            })
        })
    }

    parseDate(str) {
        // Format: MM.DD.YYYY-HH:MM:SSxxxxxx(am|pm)
        const match = str.match(/^(\d{1,2})\.(\d{1,2})\.(\d{4})-(\d{1,2}):(\d{2}).*(am|pm)$/i);
        if (!match) return null;

        const [, mm, dd, yyyy, hh, min, ampm] = match;
        const date = `${mm}/${dd}/${yyyy}`;
        const time = `${hh}:${min}${ampm.toLowerCase()}`;

        return { date, time };
    }
}

register(ForumPanel)