package org.aohe.core.twain;

import com.sun.jna.platform.win32.User32;
import com.sun.jna.platform.win32.WinDef;
import com.sun.jna.platform.win32.WinUser;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static org.aohe.core.twain.Twain.callMapper;
import static org.aohe.core.twain.Twain.execute;


public class TwainWndProc implements WinUser.WindowProc {

    private ExecutorService exec = Executors.newCachedThreadPool();

    @Override
    public WinDef.LRESULT callback(WinDef.HWND hwnd, int uMsg, final WinDef.WPARAM wParam, WinDef.LPARAM lParam) {
        switch (uMsg) {
            case WinUser.WM_CLOSE:
            case WinUser.WM_DESTROY:
                if (hwnd.equals(Twain.hwnd)) {
                    User32.INSTANCE.DestroyWindow(hwnd);
                    hwnd = null;
                    Twain.g_AppID = null;
                    Twain.done();
                }
                break;
            case WinUser.WM_USER: {
                final Object o = callMapper.get(lParam.intValue());
                if (o != null) {
//                    exec.submit(new Runnable() {
//                        @Override
//                        public void run() {
                    execute(o, wParam.intValue());
//                        }
//                    });

                }

            }
            break;
            default:
                return User32.INSTANCE.DefWindowProc(hwnd, uMsg, wParam, lParam);
        }
        return new WinDef.LRESULT(0);
    }
}
