/*
 * PVVMUD a 3D MUD
 * Copyright (C) 1998-1999  Programvareverkstedet (pvv@pvv.org)
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 */
#include "client.H"
#include <iostream.h>
#include "cliworldmanager.H"
#include "clisrvmanager.H"
#include "msgsrvcli.H"

CCliWorldManager::CCliWorldManager(CCliSrvManager * client, CCliWorldProtocol * protocol):CManager(protocol){
  m_client = client;
  getProtocol()->setName("World");

  m_pingPong = new CPingPong(MAXPINGPONG);
  m_pingCounter = 0;
  m_pingCounterMax = 0;

}

CCliWorldManager::~CCliWorldManager(){
  delete m_pingPong;
}

CCliWorldProtocol * CCliWorldManager::getProtocol(){
  return (CCliWorldProtocol*)CManager::getCommunicate();
}

CCliWorld * CCliWorldManager::getWorld(){
  return m_client->getWorld();
}

void CCliWorldManager::quit(){
  cdebug << "Connection to world server lost!\n";
}

void CCliWorldManager::hello(){
  cdebug << "Hello from world server!\n";
}

void CCliWorldManager::sendPing(){
  m_pingCounter++;

  if (m_pingCounter > m_pingCounterMax){
    if (m_pingCounterMax < MAXPINGPONG)
       m_pingCounterMax = m_pingCounter;
    m_pingCounter = 0;

    DWORD sendTime = getWorld()->getTime();

    BYTE sequenceNumber = m_pingPong->sendPing(sendTime);

    cout << "PING: " << (int)sequenceNumber
         << " time " << sendTime << endl;

    CCliWorldProtocol * protocol = getProtocol();
    protocol->sendMessage(new CMsgPing( sequenceNumber ),TRUE);
  }
}

void CCliWorldManager::pong(BYTE sequenceNumber, DWORD serverTime){
  DWORD reciveTime = getWorld()->getTime();

  long timediff = m_pingPong->recivePong(reciveTime,sequenceNumber,serverTime);

  cout << "PONG: sequence number " << (int)sequenceNumber
       << " serverTime " << serverTime
       << " recive time " << reciveTime
       << " time diff " << timediff << endl;

  cout << "Ping info " << *m_pingPong << endl;

  getWorld()->fixTime(timediff);

}