fcf.module({
  name: "fcfSimpleAuthorization:fcfSimpleAuthorization.js",
  dependencies: ["fcf:NServer/PackageHandler.js"],
  module: function(PackageHandler){
    var Namespace = fcf.prepareObject(fcf, "ModuleHandlers");

    Namespace.fcfSimpleAuthorization = function(){
      PackageHandler.call(this);

      this.initialize = function(){
        fcf.application.getRouter().append([{
            uri:        "fcfpackages/fcfSimpleAuthorization/registration-confirmation",
            controller: "fcf:NServer/NControllers/Page.js",
            source:     fcf.application.getConfiguration().fcfSimpleAuthorization_registrationCompleteTemplate,
            args:       { title: fcf.argVal("!{{Registration}}!") },
          }]);

        fcf.application.getEventChannel().on("fsql_delete", (a_event)=>{
          if (a_event.query.from != "___fcf___users")
            return;

          return fcf.actions()
          .then(()=>{
            return fcf.application.getStorage().query(
              {
                type:   "select",
                fields: [{field: "id"}],
                from:   a_event.query.from,
                where:  a_event.query.where,
                offset: a_event.query.offset,
                limit:  a_event.query.limit,
              },
              {roles: ["root"]}
            );
          })
          .then((a_records)=>{
            let query = {
              type: "delete",
              from: "___fcfSimpleAuthorization___registration_requests",
              where: [],
            };
            for(let i = 0; i < a_records[0].length; ++i)
              query.where.push({logic: "or", type: "=", args: [{field: "user"}, {value: a_records[0][i].id }]})
            return fcf.application.getStorage().query(query, {roles: ["root"]});
          })
          .catch((a_error)=>{
            fcf.log.err("fcfSimpleAuthorization", "Can't clear ___fcfSimpleAuthorization___registration_requests:", a_error);
          })
        })
      }

    }

    return Namespace.fcfSimpleAuthorization;
  }
});
