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

#define NOTIFY_MANAGE_TAB() \
{ \
  wxCommandEvent e(REFRESH_MANAGE_TAB,GetId()); \
  ProcessEvent(e); \
}

wxDECLARE_EVENT(REFRESH_MANAGE_TAB, wxCommandEvent);

BaseGameTab::BaseGameTab(wxFrame *parent, std::shared_ptr<GameBase> base)
    : TabBase_TabGames(parent),base(base) {

  glm=std::make_shared<GameListManager>(game_list);
  Reset(base);
  search_terms->SetHint("e.g: Paul Morphy");

  this->Bind(wxEVT_BUTTON, &BaseGameTab::OnDelete, this, ID_DELETE_BUTTON);
  this->Bind(wxEVT_BUTTON, &BaseGameTab::OnApplyFilter, this, ID_APPLY_FILTER_BUTTON);
  this->Bind(wxEVT_TEXT_ENTER, &BaseGameTab::OnApplyFilter, this, ID_SEARCH_TERMS);
  this->Bind(wxEVT_LIST_COL_CLICK, [g=glm](wxListEvent& e){
      g->SortBy(e.GetColumn());
  }, wxID_ANY);
}


void BaseGameTab::OnApplyFilter(wxCommandEvent &event){
  wxString terms=search_terms->GetValue();
  if(terms.length()>0){
    glm->Filter(terms.ToStdString());
  } else {
    glm->ClearFilter();
  }
}

void BaseGameTab::OnDelete(wxCommandEvent &event) {
  for(auto i: glm->GetSelectedItems()){
    game_list->SetItemState(i, 0, wxLIST_STATE_SELECTED);  // First deselect
    long gameid=glm->GetItemGameId(i);
    if(!std::count(deleted.begin(), deleted.end(), gameid)){
      deleted.push_back(gameid);
      glm->MarkItemAsDeleted(i);
    }
  }
  NOTIFY_MANAGE_TAB();
}

std::shared_ptr<Game> BaseGameTab::OpenGame(long gameid, long item) {
  game_list->SetItemState(item, 0, wxLIST_STATE_SELECTED);  // First deselect
  if(edited.find(gameid) != edited.end()){
    // TODO: Focus on the game tab and if close reopen it
    wxLogDebug("Already opened!");
  }
  else {
    std::shared_ptr<Game> g = base->GetGame(gameid);
    if(g){
      edited[gameid]=g;
      deleted.push_back(gameid);
      glm->MarkItemAsOpen(item);
      NOTIFY_MANAGE_TAB();
      return g;
    }
  }
  return nullptr;
}


std::vector<std::shared_ptr<Game>> BaseGameTab::GetEditedGames(){
  std::vector<std::shared_ptr<Game>> games;
  for(auto it = edited.begin(); it != edited.end(); it++){
    games.push_back(it->second);
  }
  return(games);
}

void BaseGameTab::Reset(std::shared_ptr<GameBase> base){
  glm->Clear();
  edited.clear();
  deleted.clear();

  // Load all games (for now :)
  SHOW_DIALOG_BUSY("Loading database...");
  this->base=base;
  if (base != nullptr) {
    while (base->NextGame()) {
      glm->AddGame(
        base->GetTag("White"),
        base->GetTag("Black"),
        base->GetTag("Event"),
        base->GetTag("Round"),
        base->GetTag("Result"),
        base->GetTag("ECO"));
    }
  }
  NOTIFY_MANAGE_TAB();
}



