/*
 * Copyright 2009 Funambol, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/* $Id$ */

#pragma once

#include "commontypes.h"
#include "downloader.h"
#include "Event.h"
#include "PortableThread.h"
#include "DaemonDM/Messenger.h"
#include "DeviceAdapter/IDeviceAdapter.h"
#include "treemanager/ActionCommand.h"
#include "serverexchange/firmware/DDProcessor.h"
#include "serverexchange/firmware/FUMODefines.h"

namespace NS_DM_Client
{
    namespace NS_Communication
    {
    	/**
    	 * FirmwareManager handles downloading and updating FW
    	 * Class supports receiving firmware DD file (mime "application/vnd.oma.dd+xml") from server.
    	 */
        class FirmwareManager : public Thread, private NS_Common::Downloader
        {
		public:
			FirmwareManager(ProfileComponentsHolder* prholder);
			virtual ~FirmwareManager();

			virtual Downloader::DownloadStatus Download();
			Downloader::DownloadStatus DownloadAndUpdate(bool update = false);

			void PerformDownload(const char *fumouri);
			void PerformDownloadAndUpdate(const char *fumouri);
			void PerformUpdate(const char *fumouri);

			void SetExecCmd(ExecPtr &cmd);
			void SetFUMOURI(const char *uri);
			void SetFWDataURI(const char *uri);
			void SetFWURL(const char *url);
			void SetServerID(const char * serverID);
			
		protected:
			
			virtual int storeBuffer(void *buffer, uint size);
			virtual void run();
			
		private:
			
			bool  m_cancelled;
			bool  m_storageInitialized;
			char *m_fumouri;
			char *m_fwDataURI;
			char *m_fwFileName;
			char *m_responseType;
			char *m_serverID;
			char *m_url;
			
			FUMOState                 m_fumoState;
			FWCmdStatus               m_fwCommandStatus;
			NS_DM_Client::IDeviceAdapter::EnumFirmwareStatus m_fwStatus;
			FWOperation               m_operation;
			DDProcessor             * m_pDDProcessor;
			NS_DM_Client::Messenger * m_pMessenger;
			ProfileComponentsHolder * m_pPCH;
			ExecPtr                   m_ExecCommand;
			NS_Common::Event          m_event;

			FUMOState doUpdate(bool resetStorage = false);
			
			bool notifyDownloadProgress();
			void notifyFWInfo();
			void notifyJobStatus();
			
			bool operationAccepted();
			void resetMessenger();
			
			// write status of fu operation into the motree
			void setFUMOStatus(FUMOState status);
			void setResponseType(const char * resptype);
			FUMOState writeFW(const char *, size_t);
			FUMOState writeFWFromFUMO();
        };
    }
}
