/*
 *  
 *  $Id$
 *  Ginkgo CADx Project
 *
 *  Copyright 2008-12 MetaEmotion S.L. All rights reserved.
 *  http://ginkgo-cadx.com
 *
 *  This file is licensed under LGPL v3 license.
 *  See License.txt for details
 *
 *
 */
#include "taskcontrol.h"
#include <main/controllers/historycontroller.h>
#include <main/controllers/controladorcomandos.h>
#include <commands/sendpacscommand.h>
#include <api/icommand.h>
#include <wx/menu.h>
#include <wx/msgdlg.h>

#define COL_DATE            0
#define COL_DESCRIPTION     1
#define COL_STATUS          2
#define COL_ERROR_MSG	    3
#define COL_ID              4

namespace GNC {
	namespace GUI {
		TaskControl::TaskControl(wxWindow* pParent, const std::list<long>& seriesPk): TaskControlBase(pParent),
			m_seriesPk(seriesPk)
		{
			RefreshTable();

			m_treeListCtrlTasks->Connect(wxEVT_COMMAND_TREE_ITEM_MENU, wxTreeEventHandler( TaskControl::OnTaskMenu ), NULL, this );
		}
		TaskControl::~TaskControl()
		{
			m_treeListCtrlTasks->Disconnect(wxEVT_COMMAND_TREE_ITEM_MENU, wxTreeEventHandler( TaskControl::OnTaskMenu ), NULL, this );
		}

		void TaskControl::RefreshTable()
		{
			std::list<GNC::GCS::HistoryController::TaskModel> tasks;
			if (m_seriesPk.empty()) {
				GNC::GCS::HistoryController::Instance()->GetAllTasks(tasks);
			} else {
				GNC::GCS::HistoryController::Instance()->GetSeriesTasks(m_seriesPk, tasks);
			}
			m_treeListCtrlTasks->DeleteRoot();
			m_treeListCtrlTasks->AddRoot(wxT("Top"));
			for (std::list<GNC::GCS::HistoryController::TaskModel>::iterator it = tasks.begin(); it != tasks.end(); it++) {
				wxDateTime taskDate;
				taskDate.ParseFormat(wxString::FromUTF8((*it).created_time.c_str()),wxT("%Y-%m-%dT%H:%M:%S"), wxDefaultDateTime);

				wxTreeItemId idNode = m_treeListCtrlTasks->AppendItem(m_treeListCtrlTasks->GetRootItem(), taskDate.Format(_("%m/%d/%Y %H:%M:%S")));
				m_treeListCtrlTasks->SetItemText(idNode, COL_DESCRIPTION, wxString::FromUTF8((*it).description.c_str()));
				switch ((*it).status) {
					case GNC::GCS::IPersistentCommand::Ok:
						m_treeListCtrlTasks->SetItemText(idNode, COL_STATUS, _("Completed"));
						break;
					case GNC::GCS::IPersistentCommand::Pending:
						m_treeListCtrlTasks->SetItemText(idNode, COL_STATUS, _("Pending"));
						break;
					case GNC::GCS::IPersistentCommand::Error:
					default:
						m_treeListCtrlTasks->SetItemText(idNode, COL_STATUS, _("Error"));
						break;
				}
				m_treeListCtrlTasks->SetItemText(idNode, COL_ERROR_MSG, wxString::FromUTF8((*it).statusDescription.c_str()));
				m_treeListCtrlTasks->SetItemText(idNode, COL_ID, wxString::Format(wxT("%d"),((*it).pk)));
			}
		}

		void TaskControl::OnRefreshClick(wxCommandEvent& /*event*/)
		{
			RefreshTable();
		}
		
		void TaskControl::OnTaskMenu(wxTreeEvent& /*event*/)
		{
			wxTreeItemId idSelected = m_treeListCtrlTasks->GetSelection();
			if (idSelected.IsOk()) {
				wxMenu menu;
				int idMenuItem = 1;
				menu.Append(idMenuItem, _("Delete task"));
				menu.Connect(idMenuItem++,wxEVT_COMMAND_MENU_SELECTED,wxCommandEventHandler( TaskControl::OnDeleteTask),NULL,this);
				menu.Append(idMenuItem, _("Restart task"));
				menu.Connect(idMenuItem++,wxEVT_COMMAND_MENU_SELECTED,wxCommandEventHandler( TaskControl::OnRestartTask),NULL,this);
				menu.Append(idMenuItem, _("Delete all"));
				menu.Connect(idMenuItem++,wxEVT_COMMAND_MENU_SELECTED,wxCommandEventHandler( TaskControl::OnDeleteAll),NULL,this);

				this->PopupMenu(&menu);
			}
		}

		void TaskControl::OnRestartTask(wxCommandEvent& /*event*/)
		{
			wxTreeItemId idSelected = m_treeListCtrlTasks->GetSelection();
			if (idSelected.IsOk()) {
				long idTask;
				m_treeListCtrlTasks->GetItemText(idSelected, COL_ID).ToLong(&idTask);
				GNC::GCS::HistoryController::TaskModel taskModel = GNC::GCS::HistoryController::Instance()->GetTask(idTask);
				//todo all tasks are sendpacs
				GADAPI::SendPACSCommand* pCmd = new GADAPI::SendPACSCommand(taskModel.pk, taskModel.seriesId);
				pCmd->init(taskModel.data);
				GNC::ControladorComandos::Instance()->ProcessAsync("",pCmd,NULL);

				RefreshTable();
			}				
		}

		void TaskControl::OnDeleteTask(wxCommandEvent& /*event*/)
		{
			wxTreeItemId idSelected = m_treeListCtrlTasks->GetSelection();
			if (idSelected.IsOk()) {
				if (wxMessageBox(_("Are you sure you want to delete tasks?"), _("Delete tasks"), wxYES_NO , this) == wxYES)
				{
					long idTask;
					m_treeListCtrlTasks->GetItemText(idSelected, COL_ID).ToLong(&idTask);
					GNC::GCS::HistoryController::TaskModel taskModel = GNC::GCS::HistoryController::Instance()->GetTask(idTask);
					std::list<GNC::GCS::HistoryController::TaskModel> taskModelList;
					taskModelList.push_back(taskModel);

					GNC::GCS::HistoryController::Instance()->DeleteTasks(taskModelList);

					RefreshTable();
				}
			}
		}

		void TaskControl::OnDeleteAll(wxCommandEvent& /*event*/)
		{
			wxTreeItemId idSelected = m_treeListCtrlTasks->GetSelection();
			if (idSelected.IsOk()) {
				if (wxMessageBox(_("Are you sure you want to delete tasks?"), _("Delete tasks"), wxYES_NO , this) == wxYES) 
				{
					std::list<GNC::GCS::HistoryController::TaskModel> tasks;
					if (m_seriesPk.empty()) {
						GNC::GCS::HistoryController::Instance()->GetAllTasks(tasks);
					} else {
						GNC::GCS::HistoryController::Instance()->GetSeriesTasks(m_seriesPk, tasks);
					}
					GNC::GCS::HistoryController::Instance()->DeleteTasks(tasks);

					RefreshTable();
				}
			}
		}
	}
}
