/*
 * 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 <base/util/ArrayList.h>
#include <vector>

#include "Event.h"
#include "IServerExchangeManager.h"
#include "PortableThread.h"

#include "executionqueue/ICommand.h"
#include "serverexchange/commands/AlertCodes.h"
#include "serverexchange/wrappers/SCommandAdapter.h"
#include "serverexchange/IConnection.h"
#include "serverexchange/ServerPoller.h"


namespace NS_DM_Client
{
	namespace NS_Common {
		class Starter;
	}

	namespace NS_Communication
	{
		class ConnectionInfo;
		class FirmwareManager;
		class SyncCall;
		class WIBConnector;
		class SEMConfig;

		/// TODO - update desc.
		/// Class implements ...
		class ServerExchangeManager : public IServerExchangeManager, private Thread
		{
		public:
			ServerExchangeManager();
			virtual ~ServerExchangeManager();

			virtual bool Init(const StringMap& settings, const String& loggerInstance, ProfileComponentsHolder& pch);
			virtual bool Start();
			virtual bool Stop();
			virtual void Release();

			virtual void AddCommand(NS_SyncMLCommand::SCommandPtr ptrCommand, const char *connid);
			virtual void AddCommands(NS_SyncMLCommand::SCommandsArray &commands, const char *connid);

			virtual IConnection * DefaultConnection();
			virtual void DefaultConnectionName(String &);

			virtual void HandleNetworkEntrance(int homeNspID, const char* operatorName, bool startWIB);
			virtual void NotifyDiagnosticsReady(String &serverID, String &origID);
			virtual void NotifyFWJobStatus(String &serverID, int result, ExecPtr &exec, const char *alertType);
			virtual bool HasAccountFor(String &serverID);
			virtual void SetConnectionsInfo(ConnInfoList &);

			virtual void ProcessBootstrapMessage(const char *bsm, uint length);
			virtual void RequestFWUpdate(bool userInitiated, const char *fumouri, int data);
			virtual void RequestSessionStart(const NS_NotificationListener::SessionInfo& sessionInfo);
			        void Restart();
			virtual void StartClientSession();
			virtual void StartClientSession(NS_SyncMLCommand::SAlertCommandPtr ptrAlert);

			virtual FirmwareManager* GetFirmwareManager();

			virtual void SetDevInfo(Funambol::DevInf &devInf);
			virtual void SetServerPollerInfo(bool pollingSupported, int pollingInterval, int pollingAttempts);

			friend class ResponseProcessor;
			friend class SEMConfig;
			
			virtual void run(); // Funambol::FThread

			virtual void StartWIB();
			
		private:
			typedef std::map<String, IConnection *> Connections;

			bool m_multipleBootstrap;
			volatile bool m_haveBMProcessed;
			volatile bool m_enteredNetwork;
			volatile bool m_startOnLAN;
			volatile bool m_startedOnLAN;
			volatile bool m_threadRunning;
			bool m_useShortTimeout;

			uint m_connectionDelay;

			struct tagPollingInfo{
				bool   pollingSupported;
				int    pollingInterval;
				int    pollingAttempts;
				tagPollingInfo() {
					pollingSupported = false;
					pollingInterval = pollingAttempts = 0;
				}
			} m_pollingInfo;

			ConnectionSettings   m_settings;
			IConnection        * m_pDefaultConnection;
			FirmwareManager    * m_pFirmwareManager;
			ProfileComponentsHolder *m_pProfileHolder;
			SyncCall           * m_pSyncCall;

			DevInfPtr            m_ptrDevInfo;
			ConnInfoList         m_connInfoList;
			Connections          m_connections;
			ServerPoller         m_serverPoller;
			String               m_defaultAccountName;
			String               m_drmdAccountName;
			String               m_OEMSharedKey;
			
			WIBConnector       * m_pWIBConnector;
			NS_Common::Starter * m_pWIBThread;
			bool                 m_wibCipherHeaderPresent;
			bool                 m_wibPlainBootstrap;
			int                  m_wibRetriesCount;
			int                  m_wibRetryInterval;
			String               m_wibDnsServer;
			String               m_wibServiceDiscoveryTarget;
			String               m_wibServer;
			int                  m_wibServerPort;
			String               m_wibRequestURI;

			// event is signaled when SEM's run() is completed
			NS_Common::Event        m_evRunComplete;

			// this mutex is locked run() is entered
			NS_Common::CritSection  m_csRun;

			// this mutex is locked when command/list of commands is added
			NS_Common::CritSection  m_csAddCommand;

			void configureDRMDAccount(ConnectionInfo &ci);
			bool isDRMDServer(const String &serverID);
			void startServerPoller();
			IConnection * getConection(const String &);
			IConnection * startConnection(const String &);
			void stopConnections();
		};
	}
}
