var utils = require("../lib/utils")
var config = require("../config")

;(function () {
    let formular = context.data.formular
    let tempForm = {}
    let formTitle = `${formular.formTitle}`
    delete formular.formTitle
    delete formular["agreement"]
    delete formular["honey"]
    formular.formRows.forEach((rowName, i) => {
        tempForm[rowName] = {}
    })
    let getValue = (e) => {
        if (e[0].includes("numberLabel")) return e[1][0]
        return e[1]
    }

    let indices = {}

    Object.entries(formular).forEach((e) => {
        if (e[0] == "formRows") return
        let key = e[0].split("_")
        let newKey = key[key.length - 1]
        let rowName = formular.formRows[Number(key[key.length - 2])]
        let index = isNaN(Number(key[key.length - 3])) ? 100 : Number(key[key.length - 3])
        if (!rowName) return
        if (!tempForm[rowName]) tempForm[rowName] = {}
        if (tempForm[rowName][newKey]) {
            tempForm[rowName][newKey][0] += "\\" + getValue(e)
        } else {
            tempForm[rowName][newKey] = [getValue(e), newKey[0] == "n", newKey.includes("invalid")]
            indices[rowName] = { ...indices[rowName], [newKey]: index }
        }
    })

    // Now iterate over tempForm to sort fields in each row
    Object.entries(tempForm).forEach(([rowName, fields]) => {
        tempForm[rowName] = Object.entries(fields)
            .sort((a, b) => indices[rowName][a[0]] - indices[rowName][b[0]])
            .reduce((acc, [key, val]) => ({ ...acc, [key]: val }), {})
    })
    console.log(JSON.stringify(tempForm), JSON.stringify(indices))

    Object.keys(tempForm).forEach((row) => {
        tempForm[row] = Object.entries(tempForm[row])
    })

    delete tempForm[undefined]
    context.smtp.sendMail({
        to: "binkrassdufass@gmail.com",
        from: "mail@webmakers.de",
        subject: "AllKids " + formTitle,
        html: context.tpl.execute(context.fs.readFile("templates/form_mail.html"), {
            context: context,
            formularRows: Object.entries(tempForm),
            formTitle: formTitle,
        }),
    })
})()
