/*
 * progress_dialog.cpp
 *
 *  Created on: 2021年10月30日
 *      Author: pengzc
 */

#include "popup_service.h"

#include "entry/EasyuiContext.h"
#include "utils/Log.h"

void NavibarSetProgressMessage(const std::string& msg);
void NavibarProgressAnimation(bool visible);
void NavibarSetDialog1Message(const std::string& msg);
void NavibarSetProgressWindowVisible(bool visible);
void NavibarSetDialog1WindowVisible(bool visible);

PopupService::PopupService() {
  busy_ = false;
}

PopupService::~PopupService() {
}

PopupService* PopupService::instance() {
  static PopupService singleton;
  return &singleton;
}

void PopupService::Dialog(const std::string& text) {
  instance()->InternalShow([text](PopupService* dialog){
    NavibarSetDialog1Message(text);
    return 0;
  }, PopupType::Dialog);
}

bool PopupService::busy() {
  return instance()->busy_;
}

void PopupService::InternalShow(const Task& func, PopupType type) {
  if (busy_) {
    LOGD("popup service is busy");
    return;
  }
  busy_ = true;
  std::thread backend([this, func, type](){
    //EASYUICONTEXT->showNaviBar();
    NavibarSetProgressMessage("");
    NavibarSetDialog1Message("");
    NavibarSetProgressWindowVisible(type == PopupType::Progress);
    NavibarSetDialog1WindowVisible(type == PopupType::Dialog);
    NavibarProgressAnimation(type == PopupType::Progress);

    int ret = func(this);
    if (type == PopupType::Progress) {
      if (0 != ret) {
        usleep(1000 * 2000);
      }

      NavibarSetProgressWindowVisible(false);

      //EASYUICONTEXT->hideNaviBar();
      busy_ = false;
    }
    NavibarProgressAnimation(false);
  });
  backend.detach();
}

void PopupService::Show(Task task) {
  LOGD("%s", __PRETTY_FUNCTION__);
  instance()->InternalShow(task, PopupType::Progress);
}

void PopupService::Show(Task task, PopupType type) {
  instance()->InternalShow(task, type);
}

void PopupService::SetMessage(const std::string& msg) {
  NavibarSetProgressMessage(msg);
}

void PopupService::Animation(bool visible) {
  NavibarProgressAnimation(visible);
}
