import m from "mithril"
import stream from "mithril/stream"
import _ from "lodash"
import powerform from "powerform"
import { required } from "validatex"
import { Card, TextField, RadioGroup, Button, Checkbox } from "polythene-mithril"
import Section from "../../models/Section"
import SectionQuestion from "../../models/SectionQuestion"
import Question from "../../models/Question"
import QuestionAnswer from "../../models/QuestionAnswer"
import Answer from "../../models/Answer"
import Respondent from "../../models/Respondent"

function findSectionOnLocalStorage() {
    var data = window.localStorage.sections
    if (!_.isEmpty(data) || !_.isNil(data)) {
        data = JSON.parse(data)
        var section = _.find(data, function(o) {
            return o.id == Section.current.data.id
        })
        if (!_.isNil(section)) return section
    }
    return false;
}

function findQuestionOnLocalStorage() {
    var section = findSectionOnLocalStorage()
    if (section != false) {
        var question = _.find(section.questions, function(o) {
            return o.id == SectionQuestion.current.data.id
        })
        if (!_.isNil(question)) return question
    }
    return false;
}

function findAnswerOnLocalStorage(questionId) {
    var question = findQuestionOnLocalStorage()
    if (question != false) {
        var answers = _.filter(question.answers, function(o) {
            return o.questionId == SectionQuestion.current.data.id
                && o.respondentId == Respondent.current.data.id
        })
        if (!_.isEmpty(answers)) return answers
    }
    return []
}

function storeAnswerToLocalStorage(answerObj) {
    var locStg = []
    if (_.isArray(answerObj.choice)) {
        var newAnswer = []
        for (var i = 0; i < answerObj.choice.length; i++) {
            newAnswer.push({
                questionId: SectionQuestion.current.data.id,
                respondentId: Respondent.current.data.id,
                questionchoiceId: answerObj.choice[i],
                text: answerObj.text
            })
        }
    } else {
        var newAnswer = {
            questionId: SectionQuestion.current.data.id,
            respondentId: Respondent.current.data.id,
            questionchoiceId: answerObj.choice,
            text: answerObj.text
        }
    }
    if (!_.isNil(window.localStorage.sections) || !_.isEmpty(window.localStorage.sections)) {
        locStg = JSON.parse(window.localStorage.sections)
        var section = _.find(locStg, function(o) {
            return o.id == Section.current.data.id
        })
        if (!_.isNil(section)) {
            var question = _.find(section.questions, function(o) {
                return o.id == SectionQuestion.current.data.id
            })
            if (!_.isNil(question)) {
                if (!_.isArray(newAnswer)) {
                    var answer = _.findIndex(question.answers, function(o) {
                        return o.respondentId == newAnswer.respondentId
                        && o.questionchoiceId == newAnswer.questionchoiceId
                    })
                    if (answer != -1) {
                        newAnswer.questionchoiceId = answerObj.choice
                        || question.answers[answer].questionchoiceId
                        newAnswer.text =  _.isUndefined(answerObj.text) ?
                        question.answers[answer].text
                        : answerObj.text
                        question.answers[answer] = newAnswer
                    } else {
                        question.answers.push(newAnswer)
                    }
                } else {
                    /* Kalau dari multichoice */
                    for (var i = 0; i < newAnswer.length; i++) {
                        var answer = _.findIndex(question.answers, function(o) {
                            return o.respondentId == newAnswer[i].respondentId
                            && o.questionchoiceId == newAnswer[i].questionchoiceId
                        })
                        if (answer != -1) question.answers[answer] = newAnswer[i]
                        else question.answers.push(newAnswer[i])
                    }
                    for (var i = 0; i < question.answers.length; i++) {
                        var answer = _.findIndex(newAnswer, function(o) {
                            return o.respondentId == question.answers[i].respondentId
                                && o.questionchoiceId == question.answers[i].questionchoiceId
                        })
                        if (answer == -1) question.answers.splice(answer, 1)
                    }
                }
            } else {
                section.questions.push({
                    id: newAnswer.questionId,
                    answers: [newAnswer]
                })
            }
        } else {
            locStg.push({
                id: Section.current.data.id,
                questions: [{
                    id: newAnswer.questionId,
                    answers: [newAnswer]
                }]
            })
        }
    } else {
        locStg.push({
            id: Section.current.data.id,
            questions: [{
                id: newAnswer.questionId,
                answers: [newAnswer]
            }]
        })
    }
    window.localStorage.sections = JSON.stringify(locStg)
    return true;
}

function retrieveAnswerFromDatabase() {
    var questionList = SectionQuestion.list.data
    var questions = []
    for (var i = 0; i < questionList.length; i++) {
        questions.push({
            id: questionList[i].id,
            answers: []
        })
        if (!_.isEmpty(questionList[i].attributes.answers)) {
            for (var o = 0; o < questionList[i].attributes.answers.length; o++) {
                questions[i].answers.push({
                    questionId: questionList[i].attributes.answers[o].question_id,
                    questionchoiceId: questionList[i].attributes.answers[o].questionchoice_id,
                    text: questionList[i].attributes.answers[o].text,
                    respondentId: questionList[i].attributes.answers[o].respondent_id,
                })
            }
        }
    }
    return questions
}

function requestAnswer(v) {
    var locStg = []
    var questions = []
    if (!_.isNil(window.localStorage.sections) || !_.isEmpty(window.localStorage.sections)) {
        var curSection = _.findIndex(JSON.parse(window.localStorage.sections), function(o) {
            return o.id == Section.current.data.id
        })
        if (curSection != -1) {
            return findAnswerOnLocalStorage()
        } else {
            locStg = JSON.parse(window.localStorage.sections)
            questions = retrieveAnswerFromDatabase()
        }
    } else {questions = retrieveAnswerFromDatabase()}
    /* Taro di localstorage */
    locStg.push({
        id: Section.current.data.id,
        questions
    })
    window.localStorage.sections = JSON.stringify(locStg)
    requestAnswer()
}

function retrieveSummary(data) {
    var question = _.find(SectionQuestion.list.data, function(o) {
        return o.id == data.id
    })
    var type = question.attributes.questionType
    if (type == "text" || type == "numeric") {
        return data.answers[0].text
    } else if (type == "choice" || type == "bool") {
        var choice = _.find(question.attributes.choices, function (o) {
            return o.id == data.answers[0].questionchoiceId
        })
        return !_.isEmpty(data.answers[0].text) ?
            choice.text + ", " + data.answers[0].text
            : choice.text
    } else if (type == "multichoice") {
        var choices = []
        for (var i = 0; i < data.answers.length; i++) {
            var choice = _.find(question.attributes.choices, function(o) {
                return o.id == data.answers[i].questionchoiceId
            })
            choices.push(choice.text)
        }
        return _.toString(choices)
    }
}

function redirectRoute(questionId) {
    SectionQuestion.current.data = !_.isNil(questionId) ?
    _.find(SectionQuestion.list.data, function(o) {
        return o.id == questionId
    })
    : SectionQuestion.list.data[0]
    return m.route.set("/sections/" + Section.current.data.id + "/questions/" + SectionQuestion.current.data.id)
}

const text = {
    form: powerform({
        req: function(v) {
            if (!v) {
                return "Tuliskan jawaban Anda"
            }
        },
    }),
    oncreate: function(vnode) {
        var answers = requestAnswer()
        text.form.req("")
        if (!_.isEmpty(answers)) {
            if (answers.length > 1) {
                var answer = _.find(answers, function(o) {
                    return o.questionchoiceId == vnode.dom.id.replace(/[^\d]+/, "")
                })
                if (!_.isNil(answer)) text.form.req(answer.text)
            }
            else text.form.req(answers[0].text)
        }
    },
    oninit: function() {
        var answers = requestAnswer()
        text.form.req(_.isEmpty(answers) ? "" : answers[0].text)
    },
    view: function(vnode) {
        var attrs = vnode.attrs || {}
        var data = attrs.data || {}
        return m(TextField, {
            id: data.elId || "question" + SectionQuestion.current.data.id,
            label: data.text || SectionQuestion.current.data.attributes.text,
            floatingLabel: true,
            help: SectionQuestion.current.data.attributes.questionType == "text"
            || SectionQuestion.current.data.attributes.questionType == "numeric" ?
            SectionQuestion.current.data.attributes.description : null,
            events: {
                oninput: function(e) {
                    text.form.req(e.target.value)
                },
                onchange: function(e) {
                    storeAnswerToLocalStorage(
                        /^mfillable\-\d+$/.test(e.target.parentNode.parentNode.id) ?
                        {text: e.target.value, choice: _.find(multichoice.form.req(), function(o) {
                            return o == e.target.parentNode.parentNode.id.replace(/[^\d]+/, "")
                        })}
                        : /^fillable\-\d+$/.test(e.target.parentNode.parentNode.id) ?
                        {text: e.target.value, choice: choice.form.req()}
                        : {text: e.target.value}
                    )
                    text.form.req(requestAnswer()[0].text)
                }
            },
            validate: function() {
                return {
                    valid: text.form.req.isValid(),
                    error: text.form.req.error()
                }
            },
            value: text.form.req()
        })
    }
}

const choice = {
    form: powerform({
        req: function(v) {
            if (!v) {
                return "Pilih salah satu jawaban di bawah ini"
            }
            var fill = _.find(SectionQuestion.current.data.attributes.choices, function(o) {
                return o.id == v
            })
            if (fill.fillable && !text.form.isValid()) {
                return "Tuliskan jawaban Anda"
            }
        }
    }),
    oninit: function() {
        var answers = requestAnswer()
        choice.form.req(_.isEmpty(answers) ? "" : answers[0].questionchoiceId)
    },
    oncreate: function() {
        SectionQuestion.current.data.attributes.choices.map(function(c) {
            if (c.fillable) {
                var child = document.createElement("span")
                // child.style.marginTop = "1.4em"
                var input = { view: function() {
                    return m(text, {
                        data: {
                            elId: "fillable-" + c.id,
                            text: "Tuliskan"
                        }
                    })
                }}
                /* Get parent */
                var parent = document.getElementById("choice-" + c.id).childNodes[0]
                parent.appendChild(child)
                m.mount(parent.querySelector("span"), input)
                if (!parent.querySelector("input").checked) {
                    document.getElementById("fillable-" + c.id).querySelector("input").disabled = true
                }
            }
            document.getElementById("choice-" + c.id)
            .childNodes[0].querySelector("input")
            .required = true
        })
        var answers = requestAnswer()
        choice.form.req(_.isEmpty(answers) ? "" : answers[0].questionchoiceId)
    },
    view: function(vnode) {
        return [
            m("div", {
                style: {
                    color: "rgba(0, 0, 0, .4)",
                    fontSize: "16px",
                    fontWeight: "400",
                    lineHeight: "24px",
                    marginTop: ".5em"
                }
            }, SectionQuestion.current.data.attributes.text + " *"),
            _.isNil(SectionQuestion.current.data.attributes.description) ?
                null : m("i", {
                style: {
                    color: "rgba(0, 0, 0, .4)"
                }
            }, "(" + SectionQuestion.current.data.attributes.description + ")"),
            m(RadioGroup, {
                id: "choices" + SectionQuestion.current.data.id,
                all: {name: SectionQuestion.current.data.attributes.questionType},
                className: "flex",
                style: {
                    margin: ".5rem 0",
                    flexFlow: "row wrap"
                },
                buttons: SectionQuestion.current.data.attributes.choices.map(function(c) {
                    return {
                        id: "choice-" + c.id,
                        value: c.id,
                        label: c.text,
                        defaultChecked: c.id == choice.form.req(),
                        checked: c.id == choice.form.req(),
                        style: {
                            marginTop: ".5em",
                            marginBottom: ".5em",
                            marginRight: "0",
                            flexGrow: "1",
                            flexBasis: "100%"
                        }
                    }
                }),
                onChange: function(state) {
                    var chosen = _.find(SectionQuestion.current.data.attributes.choices, function(o) { return o.id == state.value })
                    var target = document.getElementById("fillable-" + chosen.id)
                    if (chosen.fillable) {
                        target.querySelector("input").disabled = false
                        target.querySelector("input").focus()
                    } else {
                        SectionQuestion.current.data.attributes.choices.map(function(c) {
                            var target = document.getElementById("fillable-" + c.id)
                            if (!_.isNil(target)) {
                                target.querySelector("input").disabled = true
                                text.form.req("")
                            }
                        })
                    }

                    storeAnswerToLocalStorage({text: "", choice: state.value})
                    choice.form.req(requestAnswer()[0].questionchoiceId)
                }
            })
        ]
    }
}

const bool = {
    form: powerform({
        req: function(v) {
            if (v == null || v == "") {
                return "Pilih salah satu jawaban di bawah ini"
            }
        }
    }),
    oninit: function() {
        var answers = requestAnswer()
        bool.form.req(_.isEmpty(answers) ? "" : answers[0].questionchoiceId)
    },
    oncreate: function() {
        var answers = requestAnswer()
        bool.form.req(_.isEmpty(answers) ? "" : answers[0].questionchoiceId)
    },
    view: function() {
        return [
            m("div", {
                style: {
                    color: "rgba(0, 0, 0, .4)",
                    fontSize: "16px",
                    fontWeight: "400",
                    lineHeight: "24px",
                    marginTop: ".5em"
                }
            }, SectionQuestion.current.data.attributes.text + " *"),
            _.isNil(SectionQuestion.current.data.attributes.description) ?
                null : m("i", {
                style: {
                    color: "rgba(0, 0, 0, .4)"
                }
            }, "(" + SectionQuestion.current.data.attributes.description + ")"),
            m(RadioGroup, {
                id: "bool" + SectionQuestion.current.data.id,
                all: {name: SectionQuestion.current.data.attributes.questionType},
                className: "flex",
                style: {
                    margin: ".5rem 0",
                    flexFlow: "row wrap"
                },
                buttons: [{label: "Benar", value: 1}, {label: "Salah", value: 0}].map(function(o) {
                    return {
                        id: "true",
                        label: o.label,
                        value: o.value,
                        defaultChecked: o.value == bool.form.req(),
                        style: {
                            marginTop: ".5em",
                            marginBottom: ".5em",
                            marginRight: "0",
                            flexGrow: "1",
                            flexBasis: "100%"
                        }
                    }
                }),
                onChange: function(state) {
                    // bool.form.req(Boolean(state.value).toString())
                    console.log(state.value);
                }
            })
        ]
    }
}

const numeric = {
    form: powerform({
        req: function(v) {
            if (v == null || v == "") {
                return "Pertanyaan ini harus dijawab"
            } else if (/[^\d]+/.test(v)) {
                return "Gunakan angka"
            }
        }
    }),
    oninit: function() {
        var answers = requestAnswer()
        text.form.req(_.isEmpty(answers) ? "" : answers[0].text)
    },
    oncreate: function() {
        var answers = requestAnswer()
        text.form.req(_.isEmpty(answers) ? "" : answers[0].text)
    },
    view: function(vnode) {
        var attrs = vnode.attrs
        var data = attrs.data || {}
        return m(TextField, {
            id: data.elId || "question" + SectionQuestion.current.data.id,
            label: SectionQuestion.current.data.attributes.text,
            floatingLabel: true,
            help: Section.current.data.attributes.description,
            onChange: function(state) {
                storeAnswerToLocalStorage({text: state.value, choice: null})
                text.form.req(answers[0].text)
            },
            validate: function() {
                return {
                    valid: numeric.form.req.isValid(),
                    error: numeric.form.req.error()
                }
            },
            value: numeric.form.req()
        })
    }
}

const multichoice = {
    form: powerform({
        req: function(v) {
            if (_.isEmpty(v) || _.isNil(v)) {
                return "Pilih minimal 1 jawaban"
            }
            var item = _.find(SectionQuestion.current.data.attributes.choices, function(o) {
                return o.fillable
            })
            if (
                _.find(v, function(o) { return o == item.id }) != undefined
                && _.isEmpty(document.getElementById("mfillable-" + item.id)
                .querySelector("input").value)
            ) {
                return "Tuliskan jawaban Anda"
            }
        }
    }),
    oninit: function() {
        var answers = requestAnswer()
        multichoice.form.req(answers)
    },
    oncreate: function(vnode) {
        SectionQuestion.current.data.attributes.choices.map(function(c) {
            if (c.fillable) {
                var child = document.createElement("span")
                // child.style.marginTop = "1.4em"
                var input = { view: function() {
                    return m(text, {
                        data: {
                            elId: "mfillable-" + c.id,
                            text: "Tuliskan",
                            float: false
                        }
                    })
                }}
                /* Get parent */
                var parent = document.getElementById("mchoice-" + c.id).childNodes[0]
                parent.appendChild(child)
                m.mount(parent.querySelector("span"), input)
                var curChoice = _.findIndex(multichoice.form.req(), function(o) {
                    return o.questionchoiceId == c.id
                })
                if (curChoice == -1)
                    document.getElementById("mfillable-" + c.id).querySelector("input").disabled = true
            }
        })
        var answers = requestAnswer()
        multichoice.form.req(answers)
    },
    view: function(vnode) {
        return [
            m("div", {
                style: {
                    color: "rgba(0, 0, 0, .4)",
                    fontSize: "16px",
                    fontWeight: "400",
                    lineHeight: "24px",
                    marginTop: ".5em"
                }
            }, SectionQuestion.current.data.attributes.text + " *"),
            _.isNil(SectionQuestion.current.data.attributes.description) ?
                null : m("i", {
                style: {
                    color: "rgba(0, 0, 0, .4)"
                }
            }, "(" + SectionQuestion.current.data.attributes.description + ")"),
            m(".flex", {
                style: {marginTop: "1em", marginBottom: "1em", flexFlow: "row wrap"}
            }, SectionQuestion.current.data.attributes.choices.map(function(o) {
                return m(Checkbox, {
                    style: {margin: ".5em 0"},
                    id: "mchoice-" + o.id,
                    label: o.text,
                    value: o.id,
                    defaultChecked: _.findIndex(multichoice.form.req(), function(i) {
                        return i.questionchoiceId == o.id
                    }) != -1,
                    onChange: function(state) {
                        var choices = multichoice.form.req()
                        if (state.checked) {
                            choices.push(state.value)

                            if (o.fillable) {
                                var target =  document.getElementById("mfillable-" + o.id)
                                .querySelector("input")
                                target.disabled = false
                                target.focus()
                            }
                        } else {
                            var index = _.findIndex(choices, function(o) {
                                return o == state.value
                            })
                            choices.splice(index, 1)

                            if (o.fillable) {
                                var target =  document.getElementById("mfillable-" + o.id)
                                .querySelector("input")
                                target.disabled = true
                            }
                        }
                        storeAnswerToLocalStorage({text: "", choice: choices})
                        multichoice.form.req(choices)
                    }
                })
            }))
        ]
    }
}

window.questionType = {text, choice, bool, numeric, multichoice}

const question = {
    oninit: function(vnode) {
        if (_.isEmpty(SectionQuestion.current)) return redirectRoute(vnode.attrs.questionId)
    },
    view: function(vnode) {
        return [
            m(".header-img", {
                style: {
                    backgroundImage: "url('img/head1.jpg')"
                }
            }),
            m(".header-content", {
                style: {top: 0}
            }, m("article", {
                style: {backgroundColor: "#fff", minHeight: "100vh"}
            }, [
                m("h2.article-title", [
                    m("i.fa.fa-hashtag[aria-hidden=true]", {
                        style: {color: "rgb(255, 153, 0)", cursor: "pointer"},
                        onclick: function() {
                            m.route.set("/questionnaires/" + Section.current.data.attributes.questionnaire.id)
                        }
                    }),
                    m("div", {
                        style: {marginTop: ".3em"}
                    }, Section.current.data.attributes.title),
                ]),
                _.isNil(Section.current.data.attributes.description) ?
                    null
                    : m("h6.article-title", "(" + Section.current.data.attributes.description + ")"),
                m("h4.article-title", m("div", m("span", {style: {flexGrow: "1"}}, [
                    "Nomor: ",
                    m("input", {
                        type: "number",
                        style: {
                            width: "4em", height: "3em",
                        },
                        max: _.size(SectionQuestion.list.data),
                        min: 1,
                        placeholder: SectionQuestion.current.data.attributes.number,
                        onchange: function() {
                            var v = this.value
                            var question = _.find(SectionQuestion.list.data, function(o) {
                                return o.attributes.number == v
                            })
                            if (!_.isNil(question)) {
                                m.mount(document.getElementById("question-form__question"), null)
                                SectionQuestion.current.data = question
                                m.route.set("/sections/" + Section.current.data.id + "/questions/" + SectionQuestion.current.data.id)
                                m.mount(
                                    document.getElementById("question-form__question"),
                                    window.questionType[
                                        SectionQuestion.current
                                        .data.attributes.questionType])
                            }
                        }
                    }),
                    "/",
                    _.size(SectionQuestion.list.data)
                ]))),
                m(".flex", {
                    style: {flexFlow: "row wrap"}
                }, [
                    m(".constant"),
                    m(Card, {
                        style: {flexBasis: "80%"},
                        content: [
                            {
                                text: {
                                    content: m("form#question-form", {
                                        onsubmit: function(e) {
                                            e.preventDefault()
                                        }
                                    }, m(questionComponent))
                                }
                            }
                        ]
                    }),
                    m(".constant")
                ])
            ]))
        ]
    }
}

const questionComponent = {
    oncreate: function() {
        m.mount(
            document.getElementById("question-form__question"),
            window.questionType[
                SectionQuestion.current
                .data.attributes.questionType])
    },
    view: function() {
        return [
            m("#question-form__question"),
            m(".flex", [
                m(Button, {
                    id: "prev",
                    label: [
                        m("i.fa.fa-chevron-left.fa-fw[aria-hidden=true]"),
                        m.trust("&nbsp;"),
                        "sebelumnya"
                    ],
                    style: {
                        backgroundColor: "rgb(255, 153, 0)",
                        padding: ".8em",
                        fontSize: "14px",
                        lineHeight: "14px",
                        fontWeight: "500",
                        textTransform: "uppercase",
                        whiteSpace: "pre"
                    },
                    tone: "dark",
                    events: {
                        onclick: function() {
                            var curQuestion = _.findIndex(SectionQuestion.list.data, function(o) {
                                return o.id == SectionQuestion.current.data.id
                            })
                            var prevQuestion = SectionQuestion.list.data[curQuestion - 1]
                            if (!_.isNil(prevQuestion)) {
                                m.mount(document.getElementById("question-form__question"), null)
                                SectionQuestion.current.data = prevQuestion
                                m.route.set("/sections/" + Section.current.data.id + "/questions/" + SectionQuestion.current.data.id)
                                return m.mount(
                                    document.getElementById("question-form__question"),
                                    window.questionType[
                                        SectionQuestion.current
                                        .data.attributes.questionType]
                                )
                            }
                            return true;
                        }
                    }
                }),
                m(".flex"),
                m(Button, {
                    label: [
                        m("i.fa.fa-times.fa-fw[aria-hidden=true]"),
                        m.trust("&nbsp;"),
                        "hapus"
                    ],
                    style: {
                        backgroundColor: "rgb(255, 0, 0)",
                        padding: ".8em",
                        fontSize: "14px",
                        lineHeight: "14px",
                        fontWeight: "500",
                        textTransform: "uppercase",
                        whiteSpace: "pre"
                    },
                    tone: "dark",
                    events: {
                        onclick: function() {
                            var storage = JSON.parse(window.localStorage.sections)
                            var section = findSectionOnLocalStorage()
                            var question = findQuestionOnLocalStorage()
                            question.answers = []
                            var questionIndex = _.findIndex(section.questions, function(o) {
                                return o.id == question.id
                            })
                            section.questions[questionIndex] = question
                            var sectionIndex = _.findIndex(storage, function(o) {
                                return o.id == section.id
                            })
                            storage[sectionIndex] = section
                            m.mount(
                                document.getElementById("question-form__question"), null)
                            window.localStorage.sections = JSON.stringify(storage)
                            return m.mount(
                                document.getElementById("question-form__question"),
                                window.questionType[
                                    SectionQuestion.current
                                    .data.attributes.questionType]
                            )
                        }
                    }
                }),
                m(".flex"),
                SectionQuestion.current.data.attributes.number == _.size(SectionQuestion.list.data) ?
                m(Button, {
                    id: "finish",
                    label: [
                        "selesai",
                        m.trust("&nbsp;"),
                        m("i.fa.fa-check.fa-fw[aria-hidden=true]")
                    ],
                    style: {
                        backgroundColor: "rgb(255, 153, 0)",
                        padding: ".8em",
                        fontSize: "14px",
                        lineHeight: "14px",
                        fontWeight: "500",
                        textTransform: "uppercase",
                        whiteSpace: "pre"
                    },
                    tone: "dark",
                    events: {
                        onclick: function() {
                            m.route.set("/sections/" + Section.current.data.id + "?summary=1")
                            // m.mount(document.body, sectionSummary)
                        }
                    },
                    disabled: !_.isNil(window.localStorage.sections)
                    && !_.isNil(_.find(JSON.parse(window.localStorage.sections), function(o) {
                        return o.id == Section.current.data.id
                    }))
                    && _.size(_.filter(_.find(JSON.parse(window.localStorage.sections), function(o) {
                        return o.id == Section.current.data.id
                    }).questions, function(i) {
                        return !_.isEmpty(i.answers)
                    })) == _.size(SectionQuestion.list.data) ? false : true
                })
                : m(Button, {
                    id: "next",
                    label: [
                        "berikutnya",
                        m.trust("&nbsp;"),
                        m("i.fa.fa-chevron-right.fa-fw[aria-hidden=true]")
                    ],
                    style: {
                        backgroundColor: "rgb(255, 153, 0)",
                        padding: ".8em",
                        fontSize: "14px",
                        lineHeight: "14px",
                        fontWeight: "500",
                        textTransform: "uppercase",
                        whiteSpace: "pre"
                    },
                    tone: "dark",
                    events: {
                        onclick: function() {
                            var curQuestion = _.findIndex(SectionQuestion.list.data, function(o) {
                                return o.id == SectionQuestion.current.data.id
                            })
                            var nextQuestion = SectionQuestion.list.data[curQuestion + 1]
                            if (!_.isNil(nextQuestion)) {
                                m.mount(document.getElementById("question-form__question"), null)
                                SectionQuestion.current.data = nextQuestion
                                m.route.set("/sections/" + Section.current.data.id + "/questions/" + SectionQuestion.current.data.id)
                                return m.mount(
                                    document.getElementById("question-form__question"),
                                    window.questionType[
                                        SectionQuestion.current
                                        .data.attributes.questionType]
                                )
                            }
                            return true;
                        }
                    }
                })
            ])
        ]
    }
}

const sectionSummary = {
    curSection: {},
    oninit: function(vnode) {
        var disabled = true
        vnode.state = {disabled}

        sectionSummary.curSection = _.find(JSON.parse(window.localStorage.sections), function(i) {
            return i.id == Section.current.data.id
        })
    },
    view: function(vnode) {
        var state = vnode.state
        var disabled = state.disabled
        return [m(".header-img", {
            style: {
                backgroundImage: "url('img/head1.jpg')"
            }
        }),
        m(".header-content", {
            style: {top: 0}
        }, m("article", {
            style: {backgroundColor: "#fff", minHeight: "100vh"}
        }, [
            m("h2.article-title", [
                m("i.fa.fa-hashtag[aria-hidden=true]", {
                    style: {color: "rgb(255, 153, 0)", cursor: "pointer"},
                    onclick: function() {
                        m.route.set("/questionnaires/" + Section.current.data.attributes.questionnaire.id)
                    }
                }),
                m("div", {
                    style: {marginTop: ".3em"}
                }, Section.current.data.attributes.title),
            ]),
            _.isNil(Section.current.data.attributes.description) ?
                null
                : m("h6.article-title", "(" + Section.current.data.attributes.description + ")"),
            m("h4.article-title", "konfirmasi jawaban"),
            sectionSummary.curSection.questions.map(function(o) {
                return m(".flex", {
                    style: {flexFlow: "row wrap"}
                }, [
                    m(".constant"),
                    m(Card, {
                        style: {flexBasis: "80%"},
                        content: [
                            {
                                text: {
                                    content: [
                                        m("div", [
                                            m("span", _.find(SectionQuestion.list.data, function(v) {
                                                return v.id == o.id
                                            }).attributes.text),
                                            m("br"),
                                            m("em", "Jawaban Anda:"),
                                            m("br"),
                                            m("b", retrieveSummary(o))
                                        ])
                                    ]
                                }
                            }
                        ]
                    }),
                    m(".constant")
                ])}),
                m(".flex", {
                    style: {
                        margin: "1.5em 0 2.5em"
                    }
                }, [
                    m(".flex"),
                    m(Checkbox, {
                        label: "Dengan mencentang kolom di samping, saya mengkonfirmasi bahwa data yang saya berikan seperti yang tertera di atas benar dan sesuai.",
                        style: {
                            maxWidth: "80%"
                        },
                        onChange: function() {
                            state.disabled = !state.disabled
                        }
                    }),
                    m(".flex")
                ]),
                m(".flex", {
                    style: {marginTop: "1em", paddingBottom: "1em"}
                }, [
                    m(".flex"),
                    m(Button, {
                        id: "back",
                        label: [
                            m("i.fa.fa-chevron-left.fa-fw[aria-hidden=true]"),
                            m.trust("&nbsp;"),
                            "kembali"
                        ],
                        style: {
                            backgroundColor: "rgb(255, 153, 0)",
                            padding: ".8em",
                            fontSize: "14px",
                            lineHeight: "14px",
                            fontWeight: "500",
                            textTransform: "uppercase",
                            whiteSpace: "pre",
                        },
                        tone: "dark",
                        events: {
                            onclick: function() {
                                m.route.set("/sections/" + Section.current.data.id)
                            }
                        }
                    }),
                    m(".flex"),
                    m(Button, {
                        id: "submit",
                        label: [
                            m("i.fa.fa-upload.fa-fw[aria-hidden=true]"),
                            m.trust("&nbsp;"),
                            "kirim"
                        ],
                        style: {
                            backgroundColor: "rgb(255, 153, 0)",
                            padding: ".8em",
                            fontSize: "14px",
                            lineHeight: "14px",
                            fontWeight: "500",
                            textTransform: "uppercase",
                            whiteSpace: "pre",
                        },
                        tone: "dark",
                        events: {
                            onclick: function() {
                                _.forEach(sectionSummary.curSection.questions, function(o) {
                                    var question = _.find(SectionQuestion.list.data, function(i) {
                                        return i.id == o.id
                                    })
                                    if (question.questionType == "multichoice") {
                                        for (var i = 0; i < o.answers.length; i++) {
                                            QuestionAnswer.current = o.answers[i]
                                            QuestionAnswer.upload()
                                        }
                                    } else {
                                        QuestionAnswer.current = o.answers[0]
                                        QuestionAnswer.upload()
                                    }
                                })
                            }
                        },
                        disabled
                    }),
                    m(".flex")
                ])
            ])
        )]
    }
}

const initiator = {
    oninit: function(vnode) {
        SectionQuestion.list = []
        Section.current = {}
    },
    oncreate: function(vnode) {
        var sectionId = vnode.attrs.sectionId
        SectionQuestion.loadList(sectionId)
        Section.fetch(sectionId)
        Respondent.fetch(1)
    },
    view: function(vnode) {
        return _.isEmpty(SectionQuestion.list)
        || _.isEmpty(Section.current)
        || _.isEmpty(Respondent.current) ?
            [m(".signal"), m(".signal.late")]
            : vnode.attrs.questionId ?
                m(question, vnode.attrs)
                : vnode.attrs.summary ?
                    m(sectionSummary)
                    : redirectRoute()
    }
}

export default initiator
