
#ifndef ENGINE_H
#define ENGINE_H

#include <string>
#include <lua.hpp>
#include <map>
#include <vector>
#include <SDL.h>
#include "OdeWorld/OdeWorld.h"
#include "TextureCache/TextureCache.h"
#include "wfobj/WFObj.h"
#include "Video.h"
#include "refptr/refptr.h"
#include "ftgl.h"

class Engine
{
    public:
        class Object
        {
            public:
                Object(bool is_static, OdeWorld & world, WFObj * wfobj,
                        float scale = 1.0f);
                Object(bool is_static, OdeWorld & world,
                        OdeWorld::GeomType geom_type,
                        refptr< std::vector<float> > args);
                Object(const Object & orig);
                ~Object();

                void setPosition(double x, double y, double z)
                {
                    m_ode_object->setPosition(x, y, z);
                }
                void getPosition(double * x, double * y, double * z)
                {
                    m_ode_object->getPosition(x, y, z);
                }
                void loadPhy(const FileLoader::Path & path);
                void setVisible(bool visible) { m_is_visible = visible; }
                bool getVisible() { return m_is_visible; }
                void addForce(dReal fx, dReal fy, dReal fz)
                {
                    m_ode_object->addForce(fx, fy, fz);
                }
                void addForceRel(dReal fx, dReal fy, dReal fz)
                {
                    m_ode_object->addForceRel(fx, fy, fz);
                }
                void addTorque(dReal fx, dReal fy, dReal fz)
                {
                    m_ode_object->addTorque(fx, fy, fz);
                }
                void addTorqueRel(dReal fx, dReal fy, dReal fz)
                {
                    m_ode_object->addTorqueRel(fx, fy, fz);
                }
                void setRotation(dReal x, dReal y, dReal z)
                {
                    m_ode_object->setRotation(x, y, z);
                }
                void setColor(float r, float g, float b)
                {
                    m_color[0] = r;
                    m_color[1] = g;
                    m_color[2] = b;
                    m_color[3] = 1.0f;
                    render();
                }
                void setTexture(GLuint tex);
                void draw();
                dReal getMass() { return m_ode_object->getMass(); }
                void setMass(dReal mass) { m_ode_object->setMass(mass); }
                const float * getAABB() { return m_aabb; }

            protected:
                void createManagedObject();
                void render();

                OdeWorld::Object * m_ode_object;
                GLuint m_display_list;
                bool m_is_visible;
                float m_scale;
                bool m_is_scaled;
                bool m_is_managed;
                float m_aabb[6];

                /* for "pre-loaded" objects */
                int * m_display_list_refcnt;

                /* for "managed" objects */
                OdeWorld::GeomType  m_geom_type;
                refptr< std::vector<float> > m_args;
                float m_color[4];
                GLuint m_texture;
        };

        class EngineFileLoader : public FileLoader
        {
            public:
                EngineFileLoader(Engine * engine);
                virtual int getSize(const Path & path);
                virtual Buffer load(const Path & path);
            protected:
                std::string resolvePath(const Path & path);
                Engine * m_engine;
        };

        Engine(const std::string & path, Video & video);
        ~Engine();

        std::string locateResource(const std::string & shortname);
        bool load(const char * program);
        void run();
        void reportErrors(int status);
        OdeWorld & getWorld() { return m_world; }
        int addObject(WFObj * obj, bool is_static, float scale = 1.0f);
        int addObject(bool is_static, OdeWorld::GeomType geom_type,
                refptr< std::vector<float> > args);
        void removeObject(int id);
        int cloneObject(const Object * obj);
        Object * getObject(int id);
        void doPhysics();
        void drawObjects();
        void setAutoPhysics(bool val) { m_autoPhysics = val; }
        bool getAutoPhysics() { return m_autoPhysics; }
        void setAutoStartFrame(bool val) { m_autoStartFrame = val; }
        bool getAutoStartFrame() { return m_autoStartFrame; }
        void setAutoEndFrame(bool val) { m_autoEndFrame = val; }
        bool getAutoEndFrame() { return m_autoEndFrame; }
        void setAutoDrawObjects(bool val) { m_autoDrawObjects = val; }
        bool getAutoDrawObjects() { return m_autoDrawObjects; }
        void startFrame();
        void endFrame();
        int loadModel(const std::string & name, bool static_data,
                float scale = 1.0f);
        bool isKeyDown(const std::string & key);
        void exit();
        bool import(const char * name);
        bool importFullPath(const char * path);
        GLuint loadTexture(const char * name);
        void debug_hook(lua_Debug * debug);
        void setGravity(float gx, float gy, float gz)
        {
            m_world.setGravity(gx, gy, gz);
        }

        void getScreenSize(int * width, int * height);
        void drawText(const char * text, GLfloat r, GLfloat g, GLfloat b,
                int ptsize, float x, float y);
        void getTextSize(const char * text, int ptsize,
                float * width, float * height);
        void drawLine(float r, float g, float b,
                float x1, float y1, float x2, float y2, float width = 1.0f);
        void drawRect(float r, float g, float b,
                float width, float height, float x, float y, float rot = 0.0f);
        void fillRect(float r, float g, float b,
                float width, float height, float x, float y, float rot = 0.0f);
        void drawImage(float width, float height, float x, float y,
                int tex, float rot = 0.0f);
        void drawArc(float r, float g, float b, float x, float y,
                float radius, float a1, float a2);

        /* lua services */
        int setCamera(lua_State * L);
        int getCamera(lua_State * L);
        int registerEventHandler(lua_State * L);
        int clearEventHandler(lua_State * L);

    protected:
        static Uint32 updateCallback(Uint32 interval, void * param);

        Uint32 updateCallback(Uint32 interval);
        void registerLibraries();
        bool fileExists(const std::string & path);
        void update_event();
        void update_overlay_event();
        void key_down_event(int keysym);
        void key_up_event(int keysym);
        void mousebutton_down_event(int button, int x, int y);
        void mousebutton_up_event(int button, int x, int y);
        void mouse_motion_event(int x, int y, int xrel, int yrel);
        void checkForFunctionFull(const std::string & lua_fn_name,
                const std::string & event_name, bool & presentFlag);
        void doRegisterHandlerFull(int index,
                const std::string & event_name, bool & presentFlag);
        void reloadProgram();
        void checkForAllHandlerFunctions();

        Video &         m_video;
        TextureCache    m_textureCache;
        EngineFileLoader * m_fileLoader;
        lua_State *     m_luaState;
        std::string     m_program_path;
        std::string     m_program_directory;
        std::string     m_engine_path;
        OdeWorld        m_world;
        std::map<int, Object *> m_objects;
        int             m_next_object_index;
        int             m_next_text_index;
        GLdouble        m_eye[3];
        GLdouble        m_center[3];
        GLdouble        m_up[3];
        bool            m_drawing;
        bool            m_autoPhysics;
        bool            m_autoStartFrame;
        bool            m_autoEndFrame;
        bool            m_autoDrawObjects;
        std::map<std::string, bool> m_keysDown;
        SDL_Event       m_updateEvent;
        SDL_Event       m_exitEvent;
        Uint32          m_event_time;
        FTFont *        m_font;

        bool            m_event_init_present;
        bool            m_event_update_present;
        bool            m_event_update_overlay_present;
        bool            m_event_key_down_present;
        bool            m_event_key_up_present;
        bool            m_event_mousebutton_down_present;
        bool            m_event_mousebutton_up_present;
        bool            m_event_mouse_motion_present;
};

extern Engine * g_engine;

#endif
