#include <Misc/CloneFactory.h>

#include <IO/FileStream.h>

#include "GSEdit.h"
#include "GetEmGood.h"
#include "Level.h"



IMPLEMENT_CLONEABLE( CGSEdit, "GSEdit" )



void CGSEdit::Init()
{
  m_CurrentTile = Pac::FT_DOT;
  m_LevelNo = 1;

  m_Level.Load( GR::IO::FileStream( CMisc::AppPath( "data/level%d.dat", m_LevelNo ).c_str() ) );
}



void CGSEdit::Exit()
{
  // TODO - GUIScreen entfernen
}



void CGSEdit::UpdatePerDisplayFrame( const GR::f32 ElapsedTime )
{
  if ( theApp.InputClass()->ReleasedKeyPressed( Xtreme::KEY_ESCAPE ) )
  {
    ChangeState( "GSMenu" );
  }
  if ( theApp.InputClass()->ReleasedKeyPressed( Xtreme::KEY_F2 ) )
  {
    m_Level.Save( GR::IO::FileStream( CMisc::AppPath( "data/level%d.dat", m_LevelNo ).c_str(), IIOStream::OT_WRITE_ONLY ) );
  }
  if ( ( theApp.InputClass()->ReleasedKeyPressed( Xtreme::KEY_PLUS ) )
  ||   ( theApp.InputClass()->ReleasedKeyPressed( Xtreme::KEY_NUMPAD_PLUS ) ) )
  {
    if ( theApp.InputClass()->ShiftPressed() )
    {
      ++m_LevelNo;
      m_Level.Load( GR::IO::FileStream( CMisc::AppPath( "data/level%d.dat", m_LevelNo ).c_str() ) );
    }
    else
    {
      m_CurrentTile = (Pac::eFeldTypes)( ( m_CurrentTile + 1 ) % theApp.m_Sections.size() );
    }
  }
  if ( ( theApp.InputClass()->ReleasedKeyPressed( Xtreme::KEY_MINUS ) )
  ||   ( theApp.InputClass()->ReleasedKeyPressed( Xtreme::KEY_NUMPAD_MINUS ) ) )
  {
    if ( theApp.InputClass()->ShiftPressed() )
    {
      if ( m_LevelNo > 1 )
      {
        --m_LevelNo;
        m_Level.Load( GR::IO::FileStream( CMisc::AppPath( "data/level%d.dat", m_LevelNo ).c_str() ) );
      }
    }
    else
    {
      m_CurrentTile = ( Pac::eFeldTypes )( ( m_CurrentTile + theApp.m_Sections.size() - 1 ) % theApp.m_Sections.size() );
    }
  }
  if ( theApp.InputClass()->KeyPressed( Xtreme::MOUSE_BUTTON_1 ) )
  {
    int     tileX = theApp.InputClass()->MouseX() / 16;
    int     tileY = theApp.InputClass()->MouseY() / 16;

    m_Level.m_Field.SetField( tileX, tileY, m_CurrentTile );
  }
  if ( theApp.InputClass()->KeyPressed( Xtreme::MOUSE_BUTTON_2 ) )
  {
    int     tileX = theApp.InputClass()->MouseX() / 16;
    int     tileY = theApp.InputClass()->MouseY() / 16;

    m_CurrentTile = m_Level.m_Field.Field( tileX, tileY );
  }
}



void CGSEdit::Display( XRenderer& Renderer )
{
  m_Level.Display( Renderer, 0, 16 );

  int     x = theApp.InputClass()->MouseX();
  int     y = theApp.InputClass()->MouseY();
  Renderer.RenderTextureSection2d( x - 8, y - 8, theApp.m_Sections[m_CurrentTile] );
}



void CGSEdit::Update()
{
  // TODO - Update
}



bool CGSEdit::ProcessEvent( const GUI::OutputEvent& Event )
{
  switch ( Event.Type )
  {
    case OET_BUTTON_PUSHED:
      break;
  }
  return false;
}
