/*--------------------------------------------------------------------------*
 Project:
 File: sys_MessageLogWindow.cpp
 

*--------------------------------------------------------------------------*/
#include "sys_MessageLogWindow.h"
#include "sys_Window.h"
#include "sys_GraphicsDrawing.h"
#include <nn/gx.h>
#include <nw/ut/ut_Lock.h>

namespace uji {
namespace sys {


/*---------------------------------------------------------------------------
  Desc: コンストラクタ
  
  Args: width           1行に表示可能な文字数
        height          画面表示可能なライン数
        bufferHeight    バッファに保持可能なライン数
        fontHeight      表示する文字サイズ
---------------------------------------------------------------------------*/
MessageLogWindow::MessageLogWindow(s32 width, s32 height, s32 bufferHeight, s32 fontHeight)
  : Window("MESSAGE LOG"),
  mAutoScrollFlag(true),
  mBuffer(NULL),
  mBufferSize(0),
  mWidth(width),
  mHeight(height),  
  mLineMax(bufferHeight + 1),
  mRingTop(0),
  mPrintTop(0),
  mPrintXPos(0),    
  mY(0),
  mCyChar(fontHeight)
{
}

/*---------------------------------------------------------------------------
  Desc: デストラクタ
---------------------------------------------------------------------------*/
MessageLogWindow::~MessageLogWindow()
{
}

/*---------------------------------------------------------------------------
  Desc: バッファの確保とウインドウサイズの設定
        ※ウインドウ生成時にマネージャから呼ばれます。
---------------------------------------------------------------------------*/
bool MessageLogWindow::OnCreate()
{
    mBufferSize = (mWidth + 1) * mLineMax;
    mBuffer = new char[mBufferSize];
 
    std::memset(mBuffer, ' ', mBufferSize);
 
    GraphicsDrawing* gfx = GraphicsDrawing::GetInstance();   
    if (mCyChar == 0)
    {
        mCyChar = static_cast<int>(gfx->m_TextWriter.GetLineHeight());
    }
    Size windowSize;
    windowSize.width = (mCyChar/2)*mWidth + m_DrawOffsetX*2 + CLIENT_OUT_WIDTH;
    windowSize.height = mHeight*mCyChar + CLIENT_OUT_HEIGHT;
    SetSize(windowSize);   
    
    return true; 
}

/*---------------------------------------------------------------------------
  Desc: バッファの開放
        ※ウインドウ破棄時にマネージャから呼ばれます。
---------------------------------------------------------------------------*/
void MessageLogWindow::OnDestroy()
{
    delete[] mBuffer;    
}

/*---------------------------------------------------------------------------
  Desc: 描画処理
---------------------------------------------------------------------------*/
void MessageLogWindow::OnDraw(uji::sys::GraphicsDrawing* gfx)
{
    Window::OnDraw(gfx);
    
    if (mBuffer == NULL)
    {
        gfx->m_TextWriter.Printf("- not assign buffer -");
    }
    
    const Size clientSize = GetClientSize();
    mY = nw::ut::Clamp(
        mY,
        0,
        nw::ut::Max(0, mCyChar * GetLineCount() - clientSize.height)
    );
#if 0 // デバッグ用
    NN_LOG("Line Height= %d\n", mCyChar);    
    NN_LOG("ClientH= %d mY= %d LineCount= %d LineMax= %d\n", clientSize.height, mY, GetLineCount(), mLineMax);
#endif
    int line = mRingTop;
    int drawLine = 0;

    // ウインドウクライアント領域の位置を取得
    uji::sys::Point client_pos = this->GetClientPosition();
    
    // 文字表示開始位置の調整用
    const Point PrintOffset = Point(client_pos.x + m_DrawOffsetX, client_pos.y + m_DrawOffsetY);
    
    // 文字表示設定
    gfx->m_TextWriter.SetTextColor(nw::ut::Color8::WHITE);
    gfx->SetFixedWidthFont(static_cast<f32>(mCyChar));      
      
    gfx->BeginDrawingString();            
        while (line != mPrintTop)
        {
            int y = static_cast<int>( drawLine * mCyChar ) - mY;
#if 0       // デバッグ用
            NN_LOG("drawLine= %d y= %d\n", drawLine, y);
#endif
            // ウインドウクライアント領域内か？
            if ((0 <= y) && (y <= clientSize.height-mCyChar))
            {
                gfx->m_TextWriter.SetCursor(PrintOffset.x, PrintOffset.y + y);
                (void)gfx->m_TextWriter.Printf(GetTextPtr(line, 0));
            }

            ++drawLine;
            if (++line == mLineMax) line = 0;
        }

        // 現在の行の描画
        if ( mPrintXPos > 0 )
        {
            int y = static_cast<int>( drawLine * mCyChar ) - mY;
            if ( ( -mCyChar <= y ) && ( y <= clientSize.height ) )
            {
                gfx->m_TextWriter.SetCursor(PrintOffset.x, PrintOffset.y + y);
                (void)gfx->m_TextWriter.Printf(GetTextPtr(mPrintTop, 0));
            }
        }
    gfx->EndDrawingString();    


    // スクロールバーの表示
    {
        gfx->BeginDrawingShape();

        gfx->SetColor(nw::ut::Color8(0x303030FF));        
        gfx->FillRectangle(
            clientSize.width - 8 + client_pos.x,
            0 + client_pos.y,
            8,
            clientSize.height
        );

        int lineCount = GetLineCount();
        if ( lineCount > 0 )
        {
            gfx->SetColor(nw::ut::Color8::GRAY);        
            gfx->FillRectangle(
                clientSize.width - 7 + client_pos.x,
                mY * clientSize.height / (lineCount * mCyChar) + client_pos.y,
                6,
                nw::ut::Min(
                    clientSize.height,
                    clientSize.height * clientSize.height / (lineCount * mCyChar)
                )
            );
#if 0       // デバッグ用
            static int count_old = 0xfff;
            if (count_old != lineCount)
            {
                NN_LOG("Line: %d Y1(%d) Y2(%d)\n", lineCount, 
                    mY * clientSize.height / (lineCount * mCyChar) + client_pos.y,
                    nw::ut::Min(
                    clientSize.height,
                    clientSize.height * clientSize.height / (lineCount * mCyChar))
                );
            }     
            count_old = lineCount;
#endif            
        }
    }        
}

/*---------------------------------------------------------------------------
  Desc: パッド処理
---------------------------------------------------------------------------*/
void MessageLogWindow::OnUpdatePad(const uji::sys::Pad& pad)
{
    Window::OnUpdatePad(pad);
    
    if (mBuffer == NULL)
    {
        return;
    }
    
    const Size clientSize = GetClientSize();
    float stickY = pad.GetStick().y;
        
    // スクロール
    if ( stickY > 0 || pad.IsButtonRepeatFast( uji::sys::Pad::BUTTON_UP ) )
    {
        mY -= mCyChar;
    }
    if ( stickY < 0 || pad.IsButtonRepeatFast( uji::sys::Pad::BUTTON_DOWN ) )
    {
        mY += mCyChar;
    }
    // 先頭にジャンプ
    if ( pad.IsButtonDown( uji::sys::Pad::BUTTON_LEFT ) )
    {
        mY = 0;
    }
    // バッファの最後尾にジャンプ
    if ( pad.IsButtonDown( uji::sys::Pad::BUTTON_RIGHT ) )
    {
        mY = mCyChar * GetLineCount() - clientSize.height;
    }
}
    
/*---------------------------------------------------------------------------
  Desc: バッファへの文字出力
---------------------------------------------------------------------------*/    
void MessageLogWindow::Printf(const char* format, ...)
{
    if (mBuffer == NULL) return;

    va_list vlist;
    va_start( vlist, format );
    VPrintf( format, vlist );
    va_end( vlist );
}

void MessageLogWindow::VPrintf(const char* format, std::va_list vlist)
{
    if (mBuffer == NULL) return;

    const unsigned long STRING_BUF_SIZE = 1024; // 出力文字列生成用のバッファサイズ
    static char sStrBuf[ STRING_BUF_SIZE ];     // 出力文字列生成用のバッファ

    (void)std::vsnprintf( sStrBuf, STRING_BUF_SIZE, format, vlist );
    PutString( sStrBuf );
}

void MessageLogWindow::PutString( const char* str )
{
    NW_NULL_ASSERT( str );

    if ( mBuffer == NULL ) return;

    const Size clientSize = GetClientSize();
    
    bool canAutoScroll = false;
    if ( mCyChar * GetLineCount() <= clientSize.height ) canAutoScroll = true;
    else if ( mY == mCyChar * GetLineCount() - clientSize.height ) canAutoScroll = true;

    char* ptr = GetTextPtr( mPrintTop, mPrintXPos );

    // 一文字ずつループ
    // ソース文字列が空になるまでコピー
    while ( *str )
    {
        bool newLineFlag = false;

        if ( *str == '\n' )
        {
            str++;
            ptr = NextLine();
        }
        else
        {
            u32 bytes = PutChar( str, ptr );

            if ( bytes > 0 )
            {
                str += bytes;
                ptr += bytes;
            }
            else
            {
                newLineFlag = true;
            }
        }
        if ( mPrintXPos >= mWidth )
        {
            // 文字位置が端まで来ていたら改行フラグを立てる
            newLineFlag = true;
        }

        if ( newLineFlag )
        {
            // 次が改行文字であれば１つ読み飛ばす
            if ( *str == '\n' ) ++str;

            ptr = NextLine();
        }
    }

    // 終端にヌル文字付加
    if ( *str == '\0' )
    {
        *( GetTextPtr( mPrintTop, mPrintXPos ) ) = '\0';
    }

    // 表示位置を自動更新
    if ( mAutoScrollFlag )
    {
        if ( canAutoScroll )
        {
            mY = nw::ut::Max(0, mCyChar * GetLineCount() - clientSize.height);
        }
    }
}

unsigned long MessageLogWindow::PutChar(const char* str, char* dstPtr)
{
    unsigned long codeWidth = static_cast<unsigned long>(
        ( (u8)*str >= 0x81 ) ? 2 : 1
    );

    if (mPrintXPos + codeWidth > mWidth) return 0;

    mPrintXPos += codeWidth;

    unsigned long cnt = codeWidth;
    while ( cnt > 0 )
    {
        *dstPtr++ = *str++;
        cnt--;
    }
    return codeWidth;
}

/*---------------------------------------------------------------------------
  Desc: 指定位置のバッファのアドレスを取得
---------------------------------------------------------------------------*/    
char* MessageLogWindow::GetTextPtr(int line, int xPos)
{
    return reinterpret_cast<char*>( mBuffer ) + ( (mWidth + 1) * line + xPos );
}

/*---------------------------------------------------------------------------
  Desc: 
---------------------------------------------------------------------------*/
char* MessageLogWindow::NextLine()
{
    // 現在の行末にNUL文字を挿入
    *( GetTextPtr(  mPrintTop, mPrintXPos ) ) = '\0';

    // 出力位置を変更
    mPrintXPos = 0;
    mPrintTop++;
    if ( mPrintTop == mLineMax ) mPrintTop = 0;

    if ( mPrintTop == mRingTop )
    {
        if ( ++mRingTop == mLineMax ) mRingTop = 0;
    }
    return GetTextPtr( mPrintTop, 0 );
}

/*---------------------------------------------------------------------------
  Desc:
---------------------------------------------------------------------------*/
int MessageLogWindow::GetLineCount()
{
    int lineCount = mPrintTop - mRingTop;
    if ( lineCount < 0 ) lineCount += mLineMax;
    if ( mPrintXPos > 0 ) lineCount += 1;
    return lineCount;
}


#if 0
// TODO: 既にデータが格納されているバッファのビューアとしても使用したい。
/*---------------------------------------------------------------------------
  Desc: メッセージ格納用バッファの割り当て

  Args: buffer      文字列格納用バッファへのポインタ
        bufferSize  文字列格納用バッファのサイズ
        width       1ラインの文字数
---------------------------------------------------------------------------*/
void MessageLogWindow::AssignBuffer(void* buffer, unsigned long bufferSize, int width)
{
    mBuffer = buffer;
    mBufferSize = bufferSize;
    mWidth = width;
    mLineMax = static_cast<int>(bufferSize) / (width + 1);
}

/*---------------------------------------------------------------------------
  Desc: メッセージ格納用バッファの解放
---------------------------------------------------------------------------*/
void MessageLogWindow::ReleaseBuffer()
{
    mBuffer = NULL;
    mBufferSize = 0;
}
#endif
    

}   // usingnamespace sys
}   // usingnamespace uji
