
/**
 * @constructor
 * @param {string} hash
**/
function BookEditForm(hash) {
    /** @type {Object|null|undefined} */
    this.data = undefined;

    /** @type {String|null} */
    this.error = null;

    var _this = this;

    /** @type {Promise} */
    this.ready = new Promise((res, rej) => {
        var req = queryGet("/book/" +hash +"/info.json").then(toJSON).then((data) => {
            _this.data = {
                title: data["title"],
                author: data["author"],
                identifier: data["identifier"],
                pageCount: data["pageCount"]
            };
            res(_this);
        }).catch((e) => {
            console.error("Cannot get data from book " +hash, e);
            _this.data = null;
            this.error = e;
            res(_this);
        });
    });

    /** @type {function()} */
    this.onClose = () => {};
};

var inputType = {
    text: "text",
    number: "number"
};

BookEditForm.prototype.createInputDom = function(type, name, val) {
    switch (type) {
        case inputType.text:
        case inputType.number:
            var input = document.createElement("input");
            input.type = type;
            input.value = val || (type == inputType.text ? "" : 0);
            input.name = name;
            return input;
    }
    return null;
};

BookEditForm.prototype.createFieldDom = function(fieldName, legend, defaultValue, type) {
    var res = document.createElement("label"),
        legendDom = document.createElement("span"),
        input = this.createInputDom(type, fieldName, defaultValue);
    legendDom.textContent = legend;
    res.appendChild(legendDom);
    res.appendChild(input);
    return res;
};

BookEditForm.prototype.createDom = function() {
    var frag = document.createDocumentFragment();
    if (this.error) {
        var err = document.createElement("div");
        err.className = htmlClasses.error;
        err.textContent = this.error;
        frag.appendChild(err);
        return frag;
    }
    frag.appendChild(this.createFieldDom("title", "Titre", this.data.title, inputType.text));
    frag.appendChild(this.createFieldDom("author", "Auteur", this.data.author, inputType.text));
    frag.appendChild(this.createFieldDom("pageCount", "Nombre de pages", this.data.pageCount, inputType.number));
    frag.appendChild(this.createFieldDom("identifier", "Identifiant", this.data.identifier, inputType.text));
    return frag;
};

