#include "tab_manager.h"
#include "input_handler.h"
#include "include/cef_browser.h"
#include <algorithm>

extern void requestShutdown();

void TabManager::init(int width, int height, int cell_width, int cell_height,
                      GraphicsBackend backend, int fb_offset_x,
                      int fb_offset_y,
                      CefRefPtr<CefRequestContext> request_context, bool tiled,
                      bool show_logs) {
  width_ = width;
  height_ = height;
  cell_width_ = cell_width;
  cell_height_ = cell_height;
  backend_ = backend;
  fb_offset_x_ = fb_offset_x;
  fb_offset_y_ = fb_offset_y;
  request_context_ = request_context;
  tiled_ = tiled;
  show_logs_ = show_logs;
}

void TabManager::createTab(const std::string &url) {
  CefRefPtr<BrowserClient> c(new BrowserClient(
      width_, height_, cell_width_, cell_height_, backend_, fb_offset_x_,
      fb_offset_y_));
  c->SetTiledRenderingEnabled(tiled_);
  c->SetShowInternalConsoleLogs(show_logs_);
  c->setTabManager(this);
  if (input_handler_)
    c->setInputHandler(input_handler_);

  CefWindowInfo window_info;
  window_info.SetAsWindowless(0);

  CefBrowserSettings browser_settings;
  browser_settings.windowless_frame_rate = 30;

  CefBrowserHost::CreateBrowser(window_info, c.get(), url, browser_settings,
                                nullptr, request_context_);
  tabs_.push_back(c);

  // Focus the newly created tab.
  switchTo((int)tabs_.size() - 1);
}

void TabManager::applyActive() {
  for (auto &t : tabs_)
    t->setActive(false);

  if (active_ < 0 || (size_t)active_ >= tabs_.size()) {
    if (active_ref_)
      *active_ref_ = nullptr;
    return;
  }

  BrowserClient *cur = tabs_[active_].get();
  cur->setActive(true);

  if (active_ref_)
    *active_ref_ = tabs_[active_];

  if (input_handler_) {
    input_handler_->setBrowserClient(cur);
    input_handler_->updateBrowser(cur->GetBrowser());
  }

  // Re-blit cached frame and give the now-visible tab focus.
  cur->RedrawLastFrame();
  if (cur->GetBrowser() && cur->GetBrowser()->GetHost()) {
    cur->GetBrowser()->GetHost()->SetFocus(true);
    cur->GetBrowser()->GetHost()->Invalidate(PET_VIEW);
  }
}

void TabManager::switchTo(int idx) {
  if (idx < 0 || (size_t)idx >= tabs_.size())
    return;
  active_ = idx;
  applyActive();
}

void TabManager::next() {
  if (tabs_.empty())
    return;
  switchTo((active_ + 1) % (int)tabs_.size());
}

void TabManager::prev() {
  if (tabs_.empty())
    return;
  int n = (int)tabs_.size();
  switchTo((active_ + n - 1) % n);
}

void TabManager::tabNew() { createTab(default_url_); }
void TabManager::tabClose() { closeActiveTab(); }
void TabManager::tabNext() { next(); }
void TabManager::tabPrev() { prev(); }

void TabManager::closeActiveTab() {
  if (tabs_.empty())
    return;

  int n = (int)tabs_.size();
  if (n == 1) {
    // Last tab: closing it triggers shutdown via onTabClosed().
    BrowserClient *cur = tabs_[active_].get();
    if (cur->GetBrowser() && cur->GetBrowser()->GetHost())
      cur->GetBrowser()->GetHost()->CloseBrowser(true);
    return;
  }

  // Switch to a neighbour first so the screen shows a live tab, then close
  // the previously active one.
  int neighbour = (active_ + 1) % n;
  BrowserClient *cur = tabs_[active_].get();
  switchTo(neighbour);
  if (cur->GetBrowser() && cur->GetBrowser()->GetHost())
    cur->GetBrowser()->GetHost()->CloseBrowser(true);
}

void TabManager::closeAll() {
  for (auto &t : tabs_) {
    if (t->GetBrowser() && t->GetBrowser()->GetHost())
      t->GetBrowser()->GetHost()->CloseBrowser(true);
  }
}

void TabManager::onTabClosed(BrowserClient *closed) {
  auto it = std::find(tabs_.begin(), tabs_.end(), closed);
  if (it == tabs_.end())
    return;

  int idx = (int)(it - tabs_.begin());
  tabs_.erase(it);

  if (tabs_.empty()) {
    if (active_ref_)
      *active_ref_ = nullptr;
    requestShutdown();
    return;
  }

  if (idx < active_) {
    // Element before the active one was removed: active shifts down by one.
    active_--;
  } else if (idx == active_) {
    // Active was closed (shouldn't normally happen here, but stay valid).
    if (active_ >= (int)tabs_.size())
      active_ = (int)tabs_.size() - 1;
    if (active_ < 0)
      active_ = 0;
  }
  if (active_ >= (int)tabs_.size())
    active_ = (int)tabs_.size() - 1;
  if (active_ < 0)
    active_ = 0;

  applyActive();
}

void TabManager::resizeAll(int width, int height, int cell_width,
                           int cell_height, int fb_offset_x, int fb_offset_y) {
  width_ = width;
  height_ = height;
  cell_width_ = cell_width;
  cell_height_ = cell_height;
  fb_offset_x_ = fb_offset_x;
  fb_offset_y_ = fb_offset_y;

  for (auto &t : tabs_) {
    t->Resize(width, height, cell_width, cell_height, fb_offset_x,
              fb_offset_y);
    if (t->GetBrowser() && t->GetBrowser()->GetHost()) {
      t->GetBrowser()->GetHost()->WasResized();
      t->GetBrowser()->GetHost()->Invalidate(PET_VIEW);
    }
  }
}
