// Aseprite
// Copyright (C) 2001-2015  David Capello
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 2 as
// published by the Free Software Foundation.

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include "app/app.h"
#include "app/commands/command.h"
#include "app/commands/commands.h"
#include "app/context_access.h"
#include "app/document_access.h"
#include "app/modules/editors.h"
#include "app/ui/document_view.h"
#include "app/ui/main_window.h"
#include "app/ui/status_bar.h"
#include "app/ui/workspace.h"
#include "app/ui_context.h"
#include "doc/sprite.h"
#include "ui/ui.h"

#include <memory>

namespace app {

using namespace ui;

class CloseFileCommand : public Command {
public:
  CloseFileCommand()
    : Command("CloseFile",
              "Close File",
              CmdUIOnlyFlag) {
  }

  Command* clone() const override { return new CloseFileCommand(*this); }

protected:

  bool onEnabled(Context* context) override {
    Workspace* workspace = App::instance()->getMainWindow()->getWorkspace();
    WorkspaceView* view = workspace->activeView();
    return (view != nullptr);
  }

  void onExecute(Context* context) override {
    Workspace* workspace = App::instance()->getMainWindow()->getWorkspace();
    WorkspaceView* view = workspace->activeView();
    if (view)
      workspace->closeView(view);
  }
};

class CloseAllFilesCommand : public Command {
public:
  CloseAllFilesCommand()
    : Command("CloseAllFiles",
              "Close All Files",
              CmdRecordableFlag) {
  }

  Command* clone() const override { return new CloseAllFilesCommand(*this); }

protected:

  void onExecute(Context* context) override {
    Workspace* workspace = App::instance()->getMainWindow()->getWorkspace();

    // Collect all document views
    DocumentViews docViews;
    for (auto view : *workspace) {
      DocumentView* docView = dynamic_cast<DocumentView*>(view);
      if (docView)
        docViews.push_back(docView);
    }

    for (auto docView : docViews) {
      if (!workspace->closeView(docView))
        break;
    }
  }

};

Command* CommandFactory::createCloseFileCommand()
{
  return new CloseFileCommand;
}

Command* CommandFactory::createCloseAllFilesCommand()
{
  return new CloseAllFilesCommand;
}

} // namespace app
