var originalSerializeArray = $.fn.serializeArray;
$.fn.extend({
    serializeArray: function () {
        var brokenSerialization = originalSerializeArray.apply(this);
        var checkboxValues = $(this).find('input[type=checkbox]').map(function () {
            return { 'name': this.name, 'value': this.checked };
        }).get();
        var checkboxKeys = $.map(checkboxValues, function (element) { return element.name; });
        var withoutCheckboxes = $.grep(brokenSerialization, function (element) {
            return $.inArray(element.name, checkboxKeys) == -1;
        });

        return $.merge(withoutCheckboxes, checkboxValues);
    }
});

function generateForm() {
	$.post("/api/get_entity_info", { table: $("form").attr("data-table") }, function(data) {
		let keys = Object.keys(data);
		let h = "<fieldset>";
		for( let i = 0; i < keys.length; i++ ) {
			let key = keys[i];
			if( key == "id" ) {
				h += "<label>"+key+":<input type=\"text\" name=\"disabled_"+i+"\" placeholder=\"Automatically incremented\" aria-label=\"Automatically incremented\" disabled></label>";
				continue;
			}
			switch(data[key]) {
				case "Long":
				case "Integer":
					h += "<label>"+key+":<input type=\"number\" name=\""+key+"\" placeholder=\""+key+"\" aria-label=\""+key+"\"></label>";
					break;
				case "Float":
				case "Double":
					h += "<label>"+key+":<input type=\"number\" step=\"0.001\" name=\""+key+"\" placeholder=\""+key+"\" aria-label=\""+key+"\"></label>";
					break;
				case "String":
					h += "<label>"+key+":<input type=\"text\" name=\""+key+"\" placeholder=\""+key+"\" aria-label=\""+key+"\"></label>";
					break;
				case "Boolean":
					h += "<label><input type=\"checkbox\" name=\""+key+"\" />"+key+"</label>";
					break;
			}
		}
		h += "</fieldset><button type=\"button\" onclick=\"addEntry()\">Add</button>";
		$("form").append(h);
	});
}

function addEntry() {
	$.ajax({
	  type: "POST",
	  url: "/api/add_row",
	  data: $("form").serialize()+"&table="+$("form").attr("data-table"),
	  success: function(data, textStatus) {
		  window.location.href = "/panel?section=" + data.section;
	  },
	  error: function() {
		  $("#error_response").css("display", "");
	  }
	});
}

generateForm();