#include <windows.h>
#include <wchar.h>
#include "kbpmd_module.h"
#include "kbpmd_decoder.h"
#include "kbpmd_config.h"

#ifdef _DEBUG
#define LEAK_CHECK //メモリリーク検出（しない場合はコメントアウト）
#endif
#ifdef LEAK_CHECK
#include <crtdbg.h>
#endif

#ifdef _DEBUG
static const DWORD kbpmd_Version = 0x7FFFFFFF; //デバッグ時は優先度最大
#define KBPMD_VERSION_STR L"0x7FFFFFFF(Debug)"
#else
static const DWORD kbpmd_Version = 118; //プラグインのバージョン
#define KBPMD_VERSION_STR L"1.18"
#endif

static const wchar_t kbpmd_Description[] = L"PMD Decoder v" KBPMD_VERSION_STR " based on PMDWin.dll %s";
static const wchar_t kbpmd_Copyright[] = L"kbpmd.kpi Copyright (C) 2000-2024 Sumire Kinoshita, Kobarin\r\n"
                                         L"PMDWin.dll Copyright (C) 1999-2023 C60";

// {C09A5539-ACD7-437C-AB2A-1FD8002E45C0}
static const GUID kbpmd_GUID = 
{ 0xc09a5539, 0xacd7, 0x437c, { 0xab, 0x2a, 0x1f, 0xd8, 0x0, 0x2e, 0x45, 0xc0 } };
extern DWORD GetMultipleInstance(IKpiConfig* pConfig);
static const DWORD kbpmd_MultipleInstance = KPI_MULTINST_INFINITE;//同時に何個でも作成可能
                                           //KPI_MULTINST_ZERO;  //常に別プロセス起動
                                           //KPI_MULTINST_ONE;   //2個目以降は別プロセス起動
                                           //KPI_MULTINST_UNIQUE;//プロセスをまたいでも１つまで
                                           //KPI_MULTINST_ZERO + N;//(N+1)個目以降は別プロセス起動
                                                //↑どれか１つを選択
static const wchar_t kbpmd_SupportExts[] = L".m/.m2/.mz/.mp/.ms";
static const wchar_t kbpmd_MultiSongExts[] = L"";
static const DWORD kbpmd_SupportTagInfo = KPI_DECODER_MODULEINFO::TAG_EXTRA | 
                                          //   KPI_DECODER_MODULEINFO::TAG_TITLE;
                                          0;
static const DWORD kbpmd_SupportConfig = 1;
static void* kbpmd_Reserved1 = NULL;
static void* kbpmd_Reserved2 = NULL;

static HINSTANCE g_hKpi = NULL;
//////////////////////////////////////////////////////////////////////////////
KbPmdDecoderModule::KbPmdDecoderModule(IKpiConfig *pConfig)
    :m_ModuleInfo{
        sizeof(KPI_DECODER_MODULEINFO), //cb(=sizeof(KPI_DECODER_MODULEINFO))
        KPI_DECODER_MODULE_VERSION,     //dwModuleVersion(=KPI_DECODER_MODULE_VERSION)
        kbpmd_Version,
        kbpmd_MultipleInstance,
        kbpmd_GUID,
        kbpmd_Description,
        kbpmd_Copyright,
        kbpmd_SupportExts,
        kbpmd_MultiSongExts,
        kbpmd_Reserved1,
        kbpmd_Reserved2,
        kbpmd_SupportTagInfo,
        kbpmd_SupportConfig,
        0, 0, 0, 0                      //reserved
     }
{
    m_pConfig = pConfig;
    pConfig->AddRef();
    int nVersion;
    KbPmdDecoder::Initialize(g_hKpi, pConfig, &nVersion);
    wchar_t szVersion[32];
    if(nVersion){
        _snwprintf_s(szVersion, _TRUNCATE, L"v%d.%02d", nVersion/100, nVersion%100);
    }
    else{
        wcsncpy_s(szVersion, L"(not installed)", _TRUNCATE);
    }
    wchar_t szDescription[1024];
    swprintf_s(szDescription, _TRUNCATE, kbpmd_Description, szVersion);
    m_ModuleInfo.cszDescription = _wcsdup(szDescription);
    m_ModuleInfo.dwMultipleInstance = GetMultipleInstance(pConfig);
}
//////////////////////////////////////////////////////////////////////////////
KbPmdDecoderModule::~KbPmdDecoderModule(void)
{
    KbPmdDecoder::Uninitialize();
    m_pConfig->Release();
    free((void*)m_ModuleInfo.cszDescription);
}
//////////////////////////////////////////////////////////////////////////////
void  WINAPI KbPmdDecoderModule::GetModuleInfo(const KPI_DECODER_MODULEINFO **ppInfo)
{
    *ppInfo = &m_ModuleInfo;
}
//////////////////////////////////////////////////////////////////////////////
DWORD WINAPI KbPmdDecoderModule::Open(const KPI_MEDIAINFO *cpRequest,
                                          IKpiFile     *pFile,   //音楽データ
                                          IKpiFolder   *pFolder, //音楽データがあるフォルダ
                                          IKpiDecoder **ppDecoder)
{
    KbPmdDecoder *pDecoder = new KbPmdDecoder(m_pConfig);
    DWORD dwCount = pDecoder->Open(cpRequest, pFile, pFolder);
    if(dwCount == 0){
        *ppDecoder = NULL;
        delete pDecoder;
        return 0;
    }
    *ppDecoder = pDecoder;
    return dwCount;
}
//////////////////////////////////////////////////////////////////////////////
BOOL  WINAPI KbPmdDecoderModule::EnumConfig(IKpiConfigEnumerator *pEnumerator)
{
    //return kbfmpmd_EnumConfig(m_pConfig, pEnumerator);
    return kbpmd_EnumConfig(m_pConfig, pEnumerator);
}
//////////////////////////////////////////////////////////////////////////////
DWORD WINAPI KbPmdDecoderModule::ApplyConfig(const wchar_t *cszSection,
                                                 const wchar_t *cszKey,
                                                 INT64 nValue,
                                                 double dValue,
                                                 const wchar_t *cszValue)
{//
    //return kbfmpmd_ApplyConfig(m_pConfig, cszSection, cszKey, nValue, dValue, cszValue);
    return kbpmd_ApplyConfig(m_pConfig, cszSection, cszKey, nValue, dValue, cszValue);
}
/////////////////////////////////////////////////////////////////////////////
HRESULT WINAPI kpi_CreateInstance(REFIID riid, void **ppvObject, IKpiUnknown *pUnknown)
{
    *ppvObject = NULL;
    if(!IsEqualIID(riid, IID_IKpiDecoderModule)){
        return E_NOINTERFACE;
    }
    IKpiConfig      *pConfig = NULL;
    kpi_CreateConfig(pUnknown, &kbpmd_GUID, NULL, &pConfig);
    IKpiDecoderModule *pDecoderModule = new KbPmdDecoderModule(pConfig);
    *ppvObject = pDecoderModule;
    pConfig->Release();//KbPmdDecoderModule 内で AddRef しているので必ず必要
    return S_OK;
}
/////////////////////////////////////////////////////////////////////////////
//DllMain
/////////////////////////////////////////////////////////////////////////////
BOOL APIENTRY DllMain(HINSTANCE hModule, DWORD ul_reason_for_call, LPVOID lpReserved)
{
    switch (ul_reason_for_call) {
    case DLL_PROCESS_ATTACH:
    {
#ifdef LEAK_CHECK
        //メモリリーク検出
        int tmpDbgFlag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
        //tmpDbgFlag |= _CRTDBG_DELAY_FREE_MEM_DF;
        tmpDbgFlag |= _CRTDBG_LEAK_CHECK_DF;
        //tmpDbgFlag |= _CRTDBG_CHECK_ALWAYS_DF;
        _CrtSetDbgFlag(tmpDbgFlag);
#endif
        g_hKpi = hModule;
        DisableThreadLibraryCalls(hModule);
        break;
    }
    case DLL_PROCESS_DETACH:
        break;
    }
    return TRUE;
}
/////////////////////////////////////////////////////////////////////////////
