#include "GameTab.hpp"
#include <wx/clipbrd.h>

wxDEFINE_EVENT(GAME_CHANGE, wxCommandEvent);

GameTab::GameTab(wxFrame *parent, std::shared_ptr<Game> game)
    : wxPanel(parent), game(game), TabInfos(TabInfos::GAME) {
  // Splitter
  wxSplitterWindow *splitter = new wxSplitterWindow(this, wxID_ANY);
  splitter->SetSashGravity(0.8);
  // Panels
  game->BuildAndVerify();
  board_panel = new GameTabLeftPanel((wxFrame *)splitter, game);
  editor_panel = new GameTabRightPanel((wxFrame *)splitter, game);
  splitter->SplitVertically(board_panel, editor_panel);

  // Setup splitter
  wxBoxSizer *topSizer = new wxBoxSizer(wxHORIZONTAL);
  topSizer->Add(splitter, 1, wxEXPAND);
  SetSizerAndFit(topSizer);

  // Refresh panels
  RefreshTabTitle();
  board_panel->Notify(false, false);
  editor_panel->Notify();

  board_panel->Bind(wxEVT_TOOL,&GameTab::OnToolClick,this);
  Bind(GAME_CHANGE, &GameTab::OnGameChange, this, wxID_ANY);
}

void GameTab::OnToolClick(wxCommandEvent &event){
  short id=event.GetId();
  if(id==0){
    if(!related_file.size()>0){
      wxFileDialog
      newFileDialog(this, _("Save Game"), "", "",
                    "PGN files (*.pgn)|*.pgn", wxFD_SAVE|wxFD_OVERWRITE_PROMPT);
      if (newFileDialog.ShowModal() == wxID_CANCEL)
        return;
      // Create and open new db
      related_file = newFileDialog.GetPath().ToStdString();
    }
    SaveGame(related_file,game);
  } else if(id==1){
    Game *g=new Game(&(*game));
    wxGetApp().NewGame(std::shared_ptr<Game>(g));
  }
}

void GameTab::OnGameChange(wxCommandEvent &event) {
  if(event.GetEventObject() == board_panel)
    editor_panel->Notify();
  else if(event.GetEventObject() == editor_panel){
    board_panel->Notify();
    RefreshTabTitle();
  }
  else {
    editor_panel->Notify();
    board_panel->Notify();
    RefreshTabTitle();
  }
}

void GameTab::RefreshTabTitle() {
  std::string white = game->GetTag("White");
  std::string black = game->GetTag("Black");
  if (white.size() == 0 && black.size() == 0) {
    SetLabel("New Game");
  } else {
    SetLabel(white + "-" + black);
  }
  // Use this way to notify the MainFrame for the tab title:
  wxCommandEvent event(REFRESH_TAB_TITLE,GetId());
  event.SetEventObject(this);
  ProcessEvent(event);
}

void GameTab::ApplyPreferences() {
  board_panel->ApplyPreferences();
  editor_panel->ApplyPreferences();
}