// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.

#include <siacommon.h>  
#include <siadriveapp.h>
#include <include/cef_app.h>
#include <eventsystem.h>
#include <debugconsumer.h>
#include <loggingconsumer.h>
#include <siadriveconfig.h>
#include <siaapi.h>
#include <filepath.h>

using namespace Sia;
using namespace Sia::Api;

int APIENTRY wWinMain(HINSTANCE hInstance,
                      HINSTANCE hPrevInstance,
                      LPTSTR    lpCmdLine,
                      int       nCmdShow) 
{
  UNREFERENCED_PARAMETER(hPrevInstance);
  UNREFERENCED_PARAMETER(lpCmdLine);
  {
    std::shared_ptr<CSiaDriveConfig> siaDriveConfig(new CSiaDriveConfig(false));
    EventLevel eventLevel = EventLevelFromString(siaDriveConfig->GetEventLevel());
#ifdef _DEBUG
    CDebugConsumer debugConsumer;
    eventLevel = EventLevel::Debug;
#endif
    CLoggingConsumer loggingConsumer(eventLevel);
    CEventSystem::EventSystem.Start();
    CefEnableHighDPISupport();

    CefMainArgs mainArgs(hInstance);
    CefRefPtr<CSiaDriveApp> app(new CSiaDriveApp);
    int exitCode = CefExecuteProcess(mainArgs, app, nullptr);
    if (exitCode >= 0)
    {
      return exitCode;
    }
    
    if (CheckSingleInstance(L"{FC54C971-5B50-4EE5-AF98-671FEF061246}"))
    {
      if (siaDriveConfig->GetLaunchBundledSiad())
      {
        CSiaApi api(siaDriveConfig.get());
        if (api.GetServerVersion().IsNullOrEmpty())
        {
          FilePath dataPath(FilePath::GetAppDataDirectory(), "siadrive");
          dataPath.Append("data");
          dataPath.CreateDirectory();
          ExecuteProcess(siaDriveConfig.get(), FilePath("./sia/siad"), dataPath, false);
        }
      }

      CefSettings settings;
      settings.no_sandbox = true;
#ifdef _DEBUG
      settings.remote_debugging_port = 18080;
      settings.single_process = true;
      settings.command_line_args_disabled = true;
      settings.log_severity = LOGSEVERITY_VERBOSE;
#else
      settings.log_severity = LOGSEVERITY_DISABLE;
#endif
      CefInitialize(mainArgs, settings, app, nullptr);

      CefRunMessageLoop();

      CEventSystem::EventSystem.Stop();
    }
  }
  CefShutdown();

  return 0;;
}
