#ifndef _MaterialLoader_H_
#define _MaterialLoader_H_



#include "EventSubscriber.h"
#include "EventDispatcher.h"
#include "GsageDefinitions.h"
#include "DataProxy.h"

namespace Gsage {
  class OgreRenderSystem;
  class GsageFacade;

  /**
   TODO: INDEXER

   {
     "filename": {
        "checksum": "...",
        "changed": "...",
        "materials": []
     }
   }

   for(auto& file : filesystem->ls(folder)) {
     if(filesystem->extension(file) != "material") {
       continue;
     }
   }

   */

  /**
   * Custom OGRE material loader
   */
  class MaterialLoader : public EventDispatcher, public EventSubscriber<MaterialLoader>
  {
    public:
      MaterialLoader(OgreRenderSystem* render, GsageFacade* facade);

      /**
       * Loads material from any of resource folders
       *
       * @param material Material name
       * @param group Material group
       * @param background Loads material in background
       */
      bool load(const std::string& material, const std::string& group, bool background = true);

      /**
       * Indexer scans materials files to detect materials sets defined there
       *
       * @param folder Folder to scan
       */
      void scan(const std::string& folder);

    private:
      void scanFolder(const std::string& folder, std::vector<std::string>& files, const std::string extension);

      void readIndexFile();

      void writeIndexFile();

      bool onEnvUpdated(EventDispatcher* sender, const Event& event);

      void reloadIndex();

      OgreRenderSystem* mRender;
      GsageFacade* mFacade;
      DataProxy mIndex;
      std::string mWorkdir;

      struct FileInfo {
        std::string path;
        signed long modified;
        std::string folder;
      };

      typedef std::map<std::string, FileInfo> MaterialIndex;

      MaterialIndex mMaterialIndex;
  };
}

#endif
