aboutsummaryrefslogtreecommitdiff
path: root/src/base_tab/BaseTab.cpp
blob: 8b58ca94722666cd4570b60fc462db1b836dcc95 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#include "BaseTab.hpp"
#include "AppendGameDialog.hpp"
#include <wx/filename.h>

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

  // Games tab
  games_tab=new BaseGameTab((wxFrame *)notebook,base,this);
  glm=games_tab->glm;
  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);
  notebook->AddPage(manage_tab, "Manage database");

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

  // Bindings
  this->Bind(OPEN_GAME_EVENT, &BaseTab::OnOpenGame, this, wxID_ANY);
  this->Bind(wxEVT_BUTTON, &BaseTab::OnSave, this, ID_SAVE_BUTTON);
}


void BaseTab::OnOpenGame(wxCommandEvent &event){
  std::shared_ptr<Game> *g = (std::shared_ptr<Game>*)event.GetClientData();
  this->game=*g;

  // Ask MainFrame to open a new game
  // TODO: Simplify that is, use wxWidget main app to do it
  wxCommandEvent newGameEvent(NEW_GAME_EVENT, GetId());
  newGameEvent.SetEventObject(this);
  newGameEvent.SetClientData((TabInfos*)this);
  ProcessEvent(newGameEvent);
}

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

void BaseTab::OpenDatabase(std::string dbpath) {
  wxFileName file(dbpath);
  wxString ext = file.GetExt().Lower();
  wxLogDebug("Here");
  if (ext == "pgn") {
    if(!file.Exists())
      PGNGameBase::CreateDatabaseFile(dbpath);
    base.reset();
    base = std::shared_ptr<GameBase>(new PGNGameBase(dbpath));
  }
}

void BaseTab::OnSave(wxCommandEvent &event) {
  // Build new games
  std::vector<std::shared_ptr<Game>> new_games=games_tab->GetEditedGames();
  for(auto g: import_tab->GetGameToImport()){
    new_games.push_back(g);
  }
  SHOW_DIALOG_BUSY("Apply all changes. Take a coffee, this process can takes time...");
  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
  OpenDatabase(base_file);
  games_tab->Reset(base);
  manage_tab->Reset(base);
  import_tab->Reset(base);
}