/*global window, rJS */
/*jslint nomen: true, indent: 2, maxerr: 3 */
(function (window, rJS, RSVP, calculatePageTitle, jIO) {
  "use strict";

  rJS(window)
    /////////////////////////////////////////////////////////////////
    // Acquired methods
    /////////////////////////////////////////////////////////////////
    .declareAcquiredMethod("updateHeader", "updateHeader")
    .declareAcquiredMethod("jio_get", "jio_get")
    .declareAcquiredMethod("jio_getAttachment", "jio_getAttachment")
    .declareAcquiredMethod("jio_allDocs", "jio_allDocs")
    .declareAcquiredMethod("getUrlFor", "getUrlFor")

    /////////////////////////////////////////////////////////////////
    // declared methods
    /////////////////////////////////////////////////////////////////
    .allowPublicAcquisition('getUrlFor', function (argument_list) {
      if (argument_list[0].command === 'change') {
        if (argument_list[0].options.page == "action") {
          return this.getUrlFor({command: 'change', options: {page: "fif_action"}});
        }
      }
      return this.getUrlFor.apply(this, argument_list);
    })
    .allowPublicAcquisition('updateHeader', function (argument_list) {
      var header_dict = {
          page_title: "File : " + this.state.document_title,
          selection_url: argument_list[0].selection_url,
          //next_url: argument_list[0].next_url,
          //previous_url: argument_list[0].previous_url,
          actions_url: argument_list[0].actions_url
        };
      return this.updateHeader(header_dict);
    })
    .onStateChange(function () {
      var gadget = this;
      return gadget.getDeclaredGadget('form_view')
        .push(function (form_gadget) {
          var view_dict = {},
              group_list = [],
              metadata = gadget.state.metadata;
          view_dict["my_title"] = {
              "title": "Title",
              "default": gadget.state.document_title,
              "key": "field_my_title"
            };
          group_list.push(["left", [["my_title"]]])
          view_dict["my_reference"] = {
              "title": "Reference",
              "default": gadget.state.reference,
              "key": "field_my_reference"
            };
          group_list.push(["right",[["my_reference"]]])
          if (metadata != null) {
            for (var i = 0, entry; entry = metadata[i]; i++) {
              var key = "my_" + entry[0].replace(" ","_"),
                  side = (i % 2 == 0) ? "left" : "right" ;
              view_dict[key] = {
                "title": entry[0],
                "default": entry[1],
                "key": "field_" + key
              };
              group_list.push([side,[[key]]])
            }
          }
          else {
            view_dict["my_metadata"] = {
              "title": "Metadata",
              "default": "No metadata available for this type of file yet",
              "key": "field_my_metadata"
            };
            group_list.push(["left",[["my_metadata"]]])
          }
          return form_gadget.render({
            erp5_document: {"_embedded": {"_view": view_dict},
              "_links": {
                "type": {
                  name: ""
                }
              }
            },
              form_definition: {
                group_list: group_list
              }
            });
        });
    })
    .declareMethod("getDescriptorContent", function (descriptorReference) {
      var url = "/erp5/getDescriptorHTMLContent?reference=" + descriptorReference,
          xmlHttp = new XMLHttpRequest();
      xmlHttp.open("GET", url, false);
      xmlHttp.send(null);
      return xmlHttp.responseText;
    })
    .declareMethod("render", function (options) {
      var gadget = this;
      return gadget.jio_get(options.jio_key)
      .push(function (result) {
        var file_info = result;
        return gadget.getDescriptorContent(file_info.reference)
        .push(function (htmlContent) {
          return gadget.changeState({"document_title" : file_info.title,
                                     "reference" : file_info.reference,
                                     "textcontent" : htmlContent});
        });
      });
    })
    .declareService(function () {
      var content = this.state.textcontent.replace('<table class="table table-hover">', '<table id="table_custom_id" class="table table-hover">'),
          metadata = [];
      document.getElementById("html_report").innerHTML = content;
      if (document.getElementById("table_custom_id") === null) {
        document.getElementById("html_report").innerHTML = "";
        return;
      }
      var table = document.getElementById("table_custom_id");
      document.getElementById("html_report").innerHTML = "";
      for (var i = 0, row; row = table.rows[i]; i++) {
        metadata.push([row.cells[0].innerHTML, row.cells[1].innerHTML]);
      }
      return this.changeState({"metadata" : metadata });
    });
}(window, rJS, RSVP, calculatePageTitle, jIO));









