fcf.module({
  name: "fcf:NServer/NControllers/Page.js",
  dependencies: ["fcf:NServer/NServer.js",
                 "fcf:NServer/NControllers/Controller.js",
                 "fcf:NEvent/PreprocessControllerTmpl.js",
                 ],
  module: function(NServer, Controller, EventPreprocessControllerTmpl) {
    fcf.prepareObject(fcf, "NServer.NControllers");

    NServer.NControllers.Page = class Page extends Controller {

      constructor(a_options) {
        super(a_options);
        this.packagesArg = {};
        this._options = fcf.append(
                        {
                          args: {},
                          controller: "fcf:NServer/NControllers/Page.js",
                          source: "",
                        },
                        this._options,
                        a_options
                      );
        this.userImportance = true;
      }

      action(a_request) {
        let self = this;
        let actions = fcf.actions();
        let preprocessControllerTmpl = new EventPreprocessControllerTmpl({
          owner: self,
          actions: actions,
          packagesArg: self.packagesArg,
          request: a_request,
        });
        fcf.application.getEventChannel().send(preprocessControllerTmpl);
        actions.then(()=>{
          self._action(a_request);
        });
        actions.catch((a_error)=>{
          self._action(a_request, a_error);
        });
      }

      _action(a_request, a_errorAction) {
        let self = this;
        if (a_errorAction){
          a_request.sendErrorPage(a_errorAction);
          return;
        }

        let render = fcf.application.getRender();

        let modules = {};
        for(let k in fcf.settings.libraries) {
          let uri = fcf.getPath(k+":", false);
          modules[k] = uri.substr(0, 1) != "/" ? "/" + uri : uri;
        }

        let args = fcf.append({}, this._options.args);

        fcf.application.getRender().render( {
                                          template: this._options.source,
                                          args:     args,
                                          root:     true,
                                          route:    a_request.getRouteData(),
                                          request:  a_request,
                                          context:  fcf.getContext(),
                                          onResult: function(a_error, a_template) {
                                              if (a_error) {
                                                a_request.sendErrorPage(a_error);
                                                return;
                                              }
                                              a_request.send(a_template.content);
                                            }
                                          } );
      }
    }

    return NServer.NControllers.Page;
  }
});
