#include <DBListbox.h>
#include <SQLiteCommand.h>
#include <strtool.h>

DBListBox::DBListBox()
    : DBControl()
{
}

void DBListBox::PreCreate(CREATESTRUCT &cs)
{
    cs.style |= WS_CHILD | WS_BORDER | WS_VISIBLE | WS_VSCROLL | LBS_NOTIFY;
    cs.lpszClass = _T("listbox");
}

void DBListBox::loadData()
{
    ::SendMessage(m_hWnd, LB_RESETCONTENT, 0, 0);

    SQLiteCommand cmd(query, database->getConnection());
    SQLiteDataReader reader = cmd.ExecuteReader();
    while (reader.Read()) 
    {
        int key = atoi(reader[keyName.c_str()]);
        std::string s = getDisplayText(reader);
        WCHAR name[512];
        StrTool::utf8ToUtf16(name, 512, (unsigned char*)s.c_str());
        int idx = ::SendMessage(m_hWnd, LB_ADDSTRING, 0, (LPARAM)name);
        ::SendMessage(m_hWnd, LB_SETITEMDATA, idx, (LPARAM)key);
    }
    reader.Close();

}

std::string DBListBox::getDisplayText(SQLiteDataReader& reader)
{
    return reader[valueName.c_str()];
}

