fcf.module({
  name: "fcf:NSystem/NPackage/ThemePackage.js",
  dependencies: ["fcf:NSystem/NPackage/Package.js", "fcf:NSystem/NPackage/Theme.js", "fcf:NSystem/NPackage/tools.js"],
  lazy:         ["fcf:NSystem/NPackage/packageLoader.js"],
  module: function(Package, Theme, tools){
    var NPackage = fcf.prepareObject(fcf, "NSystem/NPackage");

    let initEventListenerFlag = false;

    function initEventListener(){
      if (initEventListenerFlag)
        return;
      initEventListenerFlag = true;
      fcf.application.getEventChannel().on("load_package", (a_event)=>{
        let configuration = fcf.filter(fcf.application.getConfiguration(), (a_key, a_item)=>{ return typeof a_item != "function" });
        fcf.each(NPackage.packageLoader.getThemes(), (a_key, a_theme)=>{
          a_theme.rebuild();
        })
      });
    }


    class ThemePackage extends Package {
      constructor(a_name, a_directory, a_configuration){
        super(a_name, a_directory, a_configuration);
        this._handlerFile = "theme.js";
        this._theme = new Theme(a_name, a_configuration);
        initEventListener();
      }

      isTheme() {
        return true;
      }

      rebuild(){
        this._theme.rebuild();
      }

      getDecor(){
        return this._theme.getDecor();
      }

      getInfo(){
        return this._theme.getInfo();
      }

      getTemplate(a_mode, a_typeOrView){
        return this._theme.getTemplate(a_mode, a_typeOrView);
      }

      resolveAlias(a_path){
        return this._theme.resolveAlias(a_path);
      }

      getAliases(){
        return this._theme.getAliases();
      }

      attachView(a_mode, a_view, a_template){
        return this._theme.attachView(a_mode, a_view, a_template);
      }

      setAliases(a_aliases){
        return this._theme.setAliases(a_aliases);
      }

      async _setConfiguration() {
        if (!fcf.empty(this._configuration.extends)) {
          await NPackage.packageLoader.load(this._configuration.extends);
          let extendsTheme = NPackage.packageLoader.getThemes()[this._configuration.extends];
          tools.mergeConfiguration(this._configuration, extendsTheme.getInfo(), false);
        }

        let configuration = fcf.append({}, this._configuration);
        delete configuration.html;
        delete configuration.aliases;
        delete configuration.views;
        fcf.application.getConfiguration().appendConfiguration(configuration);
      }

    };



    NPackage.ThemePackage = ThemePackage;

    return NPackage.ThemePackage;
  }
});
