/// @file CoreInput.h
#ifndef COREINPUT_H
#define COREINPUT_H

#include <dinput.h>
#pragma comment(lib,"dxguid.lib")
#pragma comment(lib, "dinput8.lib")

/**
	@brief 입력을 위한 클래스

	현재는 키보드 입력을 처리할 수 있습니다.\n
	listenKey 함수와 clickedKey 함수를 멤버로 가집니다.
*/

class CoreInput {
	public:
		CoreInput(){
			pDInput_ = NULL;
			pDIDeviceKB_ = NULL;
			pDIDeviceMouse_ = NULL;
		}
		~CoreInput(){
			if(pDIDeviceMouse_ != NULL){ pDIDeviceMouse_->Release(); pDIDeviceMouse_ = NULL;}
			if(pDIDeviceKB_ != NULL){ pDIDeviceKB_->Release(); pDIDeviceKB_ = NULL;}
			if(pDInput_ != NULL){ pDInput_->Release(); pDInput_ = NULL;}
		}
		void initDInput(HWND _hWnd){
            //construct DInput
			if(FAILED(DirectInput8Create(GetModuleHandle(NULL),DIRECTINPUT_VERSION,
				                         IID_IDirectInput8,(void**)&pDInput_,NULL))){return;}

			if(FAILED(pDInput_->CreateDevice(GUID_SysKeyboard,&pDIDeviceKB_,NULL))){return;}
			if(FAILED(pDIDeviceKB_->SetDataFormat(&c_dfDIKeyboard))){return;}
			if(FAILED(pDIDeviceKB_->SetCooperativeLevel(_hWnd,DISCL_BACKGROUND | DISCL_NONEXCLUSIVE))){return;}
			if(FAILED(pDIDeviceKB_->Acquire())){return;}

			if(FAILED(pDInput_->CreateDevice(GUID_SysMouse,&pDIDeviceMouse_,NULL))){return;}
			if(FAILED(pDIDeviceMouse_->SetDataFormat(&c_dfDIMouse))){return;}
			if(FAILED(pDIDeviceMouse_->SetCooperativeLevel(_hWnd,DISCL_BACKGROUND | DISCL_NONEXCLUSIVE))){return;}
			if(FAILED(pDIDeviceMouse_->Acquire())){return;}
		}
		bool listenKey(int _key){
			if(FAILED(pDIDeviceKB_->GetDeviceState(sizeof(keyBuffer_),(LPVOID)&keyBuffer_))){
				pDIDeviceKB_->Acquire();
			}

			return (keyBuffer_[_key]  & 0x80) ? TRUE : FALSE;
			/*
			if(pDIDeviceMouse_->GetDeviceState(sizeof(mouseState_),(LPVOID)&mouseState_) == DIERR_INPUTLOST){
				pDIDeviceMouse_->Acquire();
			}
			if(mouseState_.rgbButtons[MOUSE_LBUTTON] & 0x80){
				mouseLx_ += mouseState_.lX;
				mouseLy_ += mouseState_.lY;
			}
			if(mouseState_.rgbButtons[MOUSE_RBUTTON] & 0x80){
				mouseRx_ += mouseState_.lX;
				mouseRy_ += mouseState_.lY;
			}
			mouseZ_ += mouseState_.lZ/100;
			if(mouseState_.rgbButtons[MOUSE_MBUTTON] & 0x80){
				mouseZ_ += mouseState_.lZ;
			}*/
			//if(mouseState_.rgbButtons[MOUSE_LBUTTON] & 0x80){mouseLy_ += mouseState_.ly;}
		}
		bool clickedKey(int _key){
			static bOldKey = false;
			if(listenKey(_key)){
				bOldKey = true;
			}
			if(!listenKey(_key) && bOldKey){
				bOldKey = false;
				return true;
			}else{
				return false;
			}
		}

	private:
		LPDIRECTINPUT8        pDInput_;
		LPDIRECTINPUTDEVICE8  pDIDeviceKB_;
		LPDIRECTINPUTDEVICE8  pDIDeviceMouse_;
		char keyBuffer_[256];
};
#endif