//------------------------------------------------------------------------------
// Lamp : Open source game middleware
// Copyright (C) 2004  Junpei Ohtani ( Email : junpee@users.sourceforge.jp )
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//------------------------------------------------------------------------------

/** @file
 * キーボードデバイス実装
 * @author Junpee
 */

#include "LampBasic.h"
#include "Input/Keyboard/KeyboardDevice.h"

namespace Lamp{

//------------------------------------------------------------------------------
// コンストラクタ
KeyboardDevice::KeyboardDevice() : InputDevice(false){
}
//------------------------------------------------------------------------------
// デストラクタ
KeyboardDevice::~KeyboardDevice(){
}
//------------------------------------------------------------------------------
// 初期化
bool KeyboardDevice::initialize(
	DirectInputDevice* inputDevice, HWND windowHandle){
	if(!InputDevice::initialize(inputDevice, windowHandle)){ return false; }
	// データフォーマットの指定
	if(DirectXFailed(inputDevice->SetDataFormat(&c_dfDIKeyboard))){
		ErrorOut("Keyboard::initialize() "
			"キーボードのデータフォーマット指定に失敗しました。");
		return false;
	} 
	// 優先度の指定
	if(!setCooperativeLevel(isExclusive(), isForeground())){ return false; }
	return true;
}
//------------------------------------------------------------------------------
// ポーリング
bool KeyboardDevice::polling(){
	InputDevice::polling();
	u_char state[maxKeyCount];
	HRESULT result = inputDevice_->GetDeviceState(
		sizeof(u_char) * maxKeyCount, &state);
	if(DirectXSucceeded(result)){
		for(int i = 0; i < maxKeyCount; i++){
			keyboardState_.setKeyPressed((Key)i, ((state[i] & 0x80) != 0));
		}
		return true;
	}else{
		// エラーなら入力無し
		keyboardState_.clear();
		// 深刻なエラーでないかチェック
		if((result != DIERR_INPUTLOST) && (result != DIERR_NOTACQUIRED)){
			ErrorOut("GetDeviceState()に失敗しました。");
		}else{
			// デバイス再取得
			acquire();
		}
	}
	return false;
}
//------------------------------------------------------------------------------
} // End of namespace Lamp
//------------------------------------------------------------------------------
