/*
 * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
 */
#ifndef _GLASS_APPLICATION_
#define _GLASS_APPLICATION_

#include "BaseWnd.h"
#include "Utils.h"
#include <jni.h>


class Action {
public:
    virtual void Do() = 0;
    virtual ~Action() {}
};

#define ENTER_MAIN_THREAD_AND_RETURN(RetType) \
    class _MyAction : public Action {    \
        public: \
                RetType _retValue;  \
                virtual void Do() {   \
                    _retValue = _UserDo(); \
                }   \
                RetType _UserDo()

#define ENTER_MAIN_THREAD() \
    class _MyAction : public Action {    \
        public: \
                virtual void Do()

#define LEAVE_MAIN_THREAD   \
    } _action;

#define LEAVE_MAIN_THREAD_LATER   \
    };                                      \
    _MyAction * _pAction = new _MyAction(); \
    _MyAction & _action = *_pAction;

#define ARG(var) _action.var
#define DECL_JREF(T, var) JGlobalRef<T> var
#define DECL_jobject(var) DECL_JREF(jobject, var)

#define PERFORM() GlassApplication::ExecAction(&_action)

#define PERFORM_AND_RETURN() (PERFORM(), _action._retValue)

#define PERFORM_LATER() GlassApplication::ExecActionLater(_pAction)

class GlassApplication : protected BaseWnd {
public:
    GlassApplication(jobject jrefThis);
    virtual ~GlassApplication();

    static HWND GetToolkitHWND() { return  (NULL == pInstance) ? NULL : pInstance->GetHWND(); }
    static GlassApplication *GetInstance() { return pInstance; }     
    static void ExecAction(Action *action);
    static void ExecActionLater(Action *action);
    void RegisterClipboardViewer(jobject clipboard);
    void UnregisterClipboardViewer();

    inline static DWORD GetMainThreadId()
    {
        return pInstance == NULL ? 0 : pInstance->m_mainThreadId;
    }

    static jobject EnterNestedEventLoop(JNIEnv * env);
    static void LeaveNestedEventLoop(JNIEnv * env, jobject retValue);

protected:
    virtual LRESULT WindowProc(UINT msg, WPARAM wParam, LPARAM lParam);
    virtual LPCTSTR GetWindowClassNameSuffix();

private:
    jobject m_grefThis;
    jobject m_clipboard;
    static GlassApplication *pInstance;
    HWND    m_hNextClipboardView;
    DWORD m_mainThreadId;

    // These are static because the GlassApplication instance may be
    // destroyed while the nested loop is spinning
    static bool sm_shouldLeaveNestedLoop;
    static JGlobalRef<jobject> sm_nestedLoopReturnValue;
};


#endif //_GLASS_APPLICATION_
