//Editor-Info: -*- C++ -*-
//
//Subject: TOVE project
//
//File: msg_impl.cpp
//
//Version: $Revision: 1.19 $
//
//State: $State: Exp $
//
//Date: $Date: 1999/01/21 13:06:43 $
//
//Organisation:
//      Helsinki University of Technology
//      Laboratory of Telecommunications Software and Multimedia
//
//Author:
//      Vesa-Matti Puro
//      Jussi Turunen
//
//Description:
//      See corresponding header file.
//
//Copyright:
//      Copyright 1999 Helsinki University of Technology
//      ALL RIGHTS RESERVED BETWEEN JANUARY 1996 AND JUNE 1999.
//
//Licence:
//
//
//History: 

#include <stdio.h>
#include <stdlib.h>

#ifdef HAVE_FSTREAM
#   include <fstream>
#else
#   include <fstream.h>
#endif

#include "pf/error.h"
#include "pf/debug.h"
#include "msg_impl.h"
#include "tastate.h"
#include "taprimitives.h"


//
// Method:
//
// Description:
//

pfConduit pfTestAdapter
    :: createTestAdapter(CORBA_ORB_ptr orb_,
                         const string &adaptername_,
                         taState *state_,
                         const string &PCO_,
                         const string &peerName_)
{
    pfTestAdapter *testAdapter = new pfTestAdapter (adaptername_, PCO_);
    testAdapter->saveIOR(orb_, adaptername_ + ".ref");

    //  State is used to make adapter react to taMessengers
    if (state_ != 0)
    {
        state_->setReceiver(orb_, peerName_);
        testAdapter->changeState(state_);
    }
    pfConduit newAdapter(testAdapter);
    return newAdapter;
}

pfTestAdapter :: pfTestAdapter(const string &adaptername_, 
                               const string &PCO_)
    : otMessage_skel(),
      pfAdapter(),
      _PCO(PCO_),
      _adaptername(adaptername_)
{
    return;
}

pfTestAdapter :: ~pfTestAdapter(void)
{
    return;
}

void pfTestAdapter
    :: send(const char* identifier_,
            const otMessage::SerializedMessage& message_)
{
    string identifier = identifier_;
    if (identifier.compare("$OES_START_OF_CASE") == 0)
    {
        debugString("STARTING CASE", message_[0].value.in());
    }
//    else
//    {
        taMessenger *message = new taMessenger(identifier, message_);
        debugPfUlong("Message from tester. Length ", message_.length());
        message->printData();
        toA(message);
//    }
    return;
}

otMessage::SerializedMessage* pfTestAdapter
    :: sendTwoWay(const char *, const ParameterList&)
{
    throw NotImplemented();
    return 0;
}

void pfTestAdapter :: saveIOR(CORBA_ORB_ptr orb_, const string &filename_)
{
    CORBA_String_var s = orb_->object_to_string(this);
    
    //
    // NOTE: use C FILEs rather than C++ file streams, because the
    // latter don't work with g++ when RTTI is in use
    //
    FILE *fp = fopen(filename_.c_str(), "w");
    if(fp == 0)
    {
        debugString("pfTestAdapter: can't open :", filename_);
        exit(-1);
    }
    
    fprintf(fp, "%s\n", s.in());
    fclose(fp);
    
    return;
}

string pfTestAdapter :: getPCO(void)
{
    return _PCO;
}
