#include "BaseTab.hpp"
#include <wx/filename.h>

wxDEFINE_EVENT(REFRESH_MANAGE_TAB, wxCommandEvent);

BaseTab::BaseTab(wxFrame *parent, std::string base_file)
    : TabBase(parent), TabInfos(TabInfos::BASE), base_file(base_file){
  
  // First open the database
  base=OpenDatabase(base_file);

  // Games tab
  games_tab=new BaseGameTab((wxFrame *)notebook,base);
  notebook->AddPage(games_tab, "Games list",true); // true for selecting the tab
  // Import tab
  import_tab=new BaseImportTab((wxFrame *)notebook,base,this);
  notebook->AddPage(import_tab, "Import games");
  // Manage tab
  manage_tab=new BaseManageTab((wxFrame *)notebook, base, games_tab->glm,import_tab,games_tab);
  notebook->AddPage(manage_tab, "Manage database");

  // Refresh dynamic elements of the database (tab title, available db for import etc.)
  Refresh();

  // Bindings
  this->Bind(wxEVT_BUTTON, &BaseTab::OnSave, this, ID_SAVE_BUTTON);
  this->Bind(wxEVT_LIST_ITEM_ACTIVATED, &BaseTab::OnOpenGame, this, ID_TABGAMES_GAME_LIST);
  Bind(REFRESH_MANAGE_TAB,[tab=manage_tab](wxCommandEvent &e){
      tab->RefreshInformations();
  },wxID_ANY);
}

void BaseTab::OnOpenGame(wxListEvent &event){
  long gameid=std::stol(event.GetItem().GetText().ToStdString());
  std::shared_ptr<Game> g = games_tab->OpenGame(gameid,event.GetIndex());
  if(g){
    game=g;
    wxGetApp().NewGame(this,g);
  }
}

void BaseTab::Refresh(){
  import_tab->RefreshImportLists();
  SetLabel(wxFileName(base->GetFilePath()).GetName()+" [DB]"); // Propagated to MainWindow tab title automatically by wxWidget
}

void BaseTab::OnSave(wxCommandEvent &event) {
  SHOW_DIALOG_BUSY("Apply all changes. Take a coffee, this process can takes time...");
  // First import games
  std::vector<std::shared_ptr<Game>> new_games=games_tab->GetEditedGames();
  for(auto g: import_tab->GetGameToImport()){
    new_games.push_back(g);
  }
  base->Save(games_tab->GetDeletedGameIds(), import_tab->GetDatabaseToImport(), new_games);

  // Close all opened games in this database
  wxCommandEvent closeLinkedTabEvent(CLOSE_LINKED_TAB, GetId());
  closeLinkedTabEvent.SetClientData((TabInfos*)this);
  ProcessEvent(closeLinkedTabEvent);

  // Reopen the saved database
  base.reset();
  base=OpenDatabase(base_file);
  games_tab->Reset(base);
  manage_tab->Reset(base);
  import_tab->Reset(base);
}