/*!
  \file
  \brief 音楽まわりの初期化

  \author Satofumi KAMIMURA

  $Id: Audio.cpp 1811 2010-04-30 16:12:05Z satofumi $
*/

#include "Audio.h"
#include <AL/alut.h>
#include <string>
#include <cstdlib>

using namespace qrk;
using namespace std;


struct Audio::pImpl
{
    string error_message_;
    static bool initialized_;


    pImpl(void) : error_message_("not initialized.")
    {
    }


    static pImpl* object(void)
    {
        static pImpl singleton_object;
        return &singleton_object;
    }


    bool initialize(void)
    {
        int dummy_argc = 1;
        char dummy_program[] = "dummy";
        char* dummy_argv[] = { dummy_program };
        if (alutInit(&dummy_argc, dummy_argv) < 0) {
            ALenum error = alutGetError();
            error_message_ = alutGetErrorString(error);
            return false;
        }

        initialized_ = true;
        atexit(quit);
        return true;
    }


    static void quit(void)
    {
        ALCcontext* context = alcGetCurrentContext();
        ALCdevice* device = alcGetContextsDevice(context);

        alcDestroyContext(context);
        alcCloseDevice(device);

        alutExit();
    }
};
bool Audio::pImpl::initialized_ = false;


Audio::Audio(void) : pimpl(pImpl::object())
{
}


Audio::~Audio(void)
{
}


const char* Audio::what(void) const
{
    return pimpl->error_message_.c_str();
}


bool Audio::initialize(void)
{
    return (pimpl->initialized_) ? true : pimpl->initialize();
}


bool Audio::isInitialized(void)
{
    return pimpl->initialized_;
}
