fcf.module({
  name: "fcfSimpleAuthorization:package.js",
  dependencies: ["fcf:NSystem/NPackage/PackageHandler.js"],
  module: function(PackageHandler){

    class Package extends PackageHandler {

      async initialize(){
        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}}!") },
            ignoreSiteMap:  true,
            ignoreMenu:     true,
          }]);

        fcf.application.getCron().append("Remove login_by_email records", "* * * * * master", {hidden: true}, async ()=>{
          let lastTime = new Date(new Date().getTime() - fcf.application.getConfiguration().fcfSimpleAuthorization_lifetimeLoginByEmailTemplate*60*1000);
          await fcf.application.getStorage().query(
                "DELETE FROM ___fcfSimpleAuthorization___login_by_email WHERE datetime < ${1}",
                [lastTime]
                );
        });

        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 Package;
  }
});
