#include "SMSMasterCtrlInterface.h"
#include <QByteArray>
#include <QDataStream>
#include <QBuffer>
#include "SystemGui.h"
#include "Contact.h"
#include "SMSClient.h"


CSMSMasterCtrlInterface::CSMSMasterCtrlInterface(CSMSClient *ProgramHandle)
{
    mDeviceAddress = 1;
    mNetworkPort = 2182;
    mMasterCtrlIPAddress = "127.0.0.1";
//    mNetworkPort = 6463;
   // mMasterCtrlIPAddress = "192.168.0.100";
   // mMasterCtrlIPAddress = "mortel.myftp.org";
    mNetworkCommSocket = 0;
    mMyDeviceID = ID_SMS_CLIENT;

    mProgramHandle = ProgramHandle;
}

CSMSMasterCtrlInterface::~CSMSMasterCtrlInterface()
{
    if(mNetworkCommSocket !=0)
    {
//        mNetworkCommSocket->disconnectFromHost();
   //     delete mNetworkCommSocket;
    }
}

//int CSMSMasterCtrlInterface::ConnectToMasterCtrl()
//{
////    if(mNetworkCommSocket == 0)
////    {
////        mNetworkCommSocket = new QTcpSocket();
////    }
////    connect(mNetworkCommSocket,SIGNAL(connected()),this,SLOT(NetworkSocketConnected()));
////    connect(mNetworkCommSocket,SIGNAL(disconnected()),this,SLOT(NetworkSocketDisconnected()));
////    connect(mNetworkCommSocket,SIGNAL(readyRead()),this,SLOT(NetworkSocketDataAvailable()));

////    mNetworkCommSocket->connectToHost(mMasterCtrlIPAddress,mNetworkPort);

//    return RET_OK;
//}

int CSMSMasterCtrlInterface::DeviceConnectedToMaster(bool Connected)
{
    if(Connected)
    {
         mNetworkCommSocket->write(GetTxPacket(SMS_CLIENT_DEVICE_DID_INFO_REQUEST,0,0,0,1,ID_MASTER,ID_SMS_CLIENT,mDeviceAddress));
    }
    else
    {
        //???
    }
    return RET_OK;
}

int CSMSMasterCtrlInterface::DeviceFrameReceived(int TargetDeviceID, int TargetDeviceAddress, int SenderDeviceID, int SenderAddress, int MessageID, int DataSize, QByteArray Data)
{
    Q_UNUSED(DataSize)


//    if(TargetDeviceID == ID_ETHERNET_VIRTUAL)
//    {
//        switch(MessageID)
//        {
//            case ETH_NETWK_DEVICE_INFO_REQUEST:
//            {
//                QByteArray Frame,ResponseData;
//                ResponseData.append((char)ID_SMS_CLIENT);
//                ResponseData.append((char)mDeviceAddress);
//                Frame = GetTxPacket(ETH_NETWK_DEVICE_INFO_RESPONSE,0,ResponseData.data(),ResponseData.size(),1,ID_MASTER,ID_ETHERNET_VIRTUAL,mDeviceAddress);
//                mNetworkCommSocket->write(Frame);
//                break;
//            }
//            case ETH_NETWK_CONNECTION_REFUSED:
//            {
//                qDebug("MasterCtrl connection refused");
//                mNetworkCommSocket->close();
//                delete mNetworkCommSocket;
//                mNetworkCommSocket = 0;
//                break;
//            }
//            case ETH_NETWK_SET_DEVICE_INFO_ACK:
//            {
//                mNetworkCommSocket->write(GetTxPacket(SMS_CLIENT_DEVICE_DID_INFO_REQUEST,0,0,0,1,ID_MASTER,ID_SMS_CLIENT,mDeviceAddress));
//                qDebug("MasterCtrl accepted connection");
//                break;
//            }
//            case ETH_NETWK_DEVICE_INFO_RESPONSE:
//            default:
//            {
//                break;
//            }

//        }
//    }
   /* else*/ if(TargetDeviceID == ID_SMS_CLIENT && (TargetDeviceAddress == BROADCAST_VALUE || TargetDeviceAddress == mDeviceAddress))
    {
        switch(MessageID)
        {
            case SMS_CLIENT_DEVICE_ACK:
            {
                break;
            }
            case SMS_CLIENT_DEVICE_STATUS_REQUEST:
            {
                QByteArray Frame,ResponseData;
                ResponseData.append(ACK);
                ResponseData.append((char)SMS_CLIENT_DEVICE_STATUS_REQUEST);
                Frame = GetTxPacket(SMS_CLIENT_DEVICE_STATUS_RESPONSE,0,ResponseData.data(),ResponseData.size(),1,ID_MASTER,ID_SMS_CLIENT,mDeviceAddress);
                mNetworkCommSocket->write(Frame);
         //       qDebug("Rx Status Request");
                break;
            }
            case SMS_CLIENT_DEVICE_DID_INFO_RESPONSE:
            {
                QString DidInfo;
                QDataStream *Strm = new QDataStream(Data);
                *Strm >> DidInfo;
                delete Strm;
                qDebug("Rx DID info: %s",DidInfo.toUtf8().data());
                mProgramHandle->SetDIDDatabase(DidInfo);

//                mNetworkCommSocket->write(GetTxPacket(SMS_CLIENT_DEVICE_GET_ALL_MSG_REQUEST,0,0,0,1,ID_MASTER,ID_SMS_CLIENT,mDeviceAddress));
                mNetworkCommSocket->write(GetTxPacket(SMS_CLIENT_DEVICE_GET_CONTACTS_REQUEST,0,0,0,1,ID_MASTER,ID_SMS_CLIENT,mDeviceAddress));
                break;
            }
            case SMS_CLIENT_DEVICE_GET_ALL_MSG_RESPONSE:
            {
                QList<CSMSMessage> RAWSMSList;
                QDataStream *Stream = new QDataStream(Data);
                CSMSMessage NewMsg;

                int NbMsg;
                *Stream >> NbMsg;

                for(int i = 0; i < NbMsg; i++)
                {
                    *Stream >> NewMsg;
                    RAWSMSList.append(NewMsg);
                }

                mProgramHandle->SetAllMsgsDatabase("",&RAWSMSList);

                RAWSMSList.clear();


                delete Stream;
                break;
            }
            case SMS_CLIENT_DEVICE_NEW_MSG_NOTIFICATION:
            {
                QList<CSMSMessage> RAWSMSList;
                QDataStream *Stream = new QDataStream(Data);
                CSMSMessage NewMsg;

                int NbMsg;
                *Stream >> NbMsg;

                for(int i = 0; i < NbMsg; i++)
                {
                    *Stream >> NewMsg;
                    RAWSMSList.append(NewMsg);
                }

                mProgramHandle->NewMessagesEvent(&RAWSMSList);

                RAWSMSList.clear();


                delete Stream;


                break;
            }
            case SMS_CLIENT_DEVICE_SEND_SMS_ACK:
            {

                QDataStream *Stream = new QDataStream(Data);
                qint32 Success;
                *Stream >> Success;
                if(Success == 1)
                {
                    qDebug("SMS Sent!!!");
                }
                else
                {
                    qDebug("Send SMS Failed");
                }

                delete Stream;

                break;
            }
            case SMS_CLIENT_DEVICE_GET_CONTACTS_RESPONSE:
            {
                QList<CContact> ContactsList;
                QDataStream *Stream = new QDataStream(Data);
                CContact NewContact;

                int NbContact;
                *Stream >> NbContact;

                for(int i = 0; i < NbContact; i++)
                {
                    *Stream >> NewContact;
                    ContactsList.append(NewContact);
                }

                mProgramHandle->SetContacts(&ContactsList);

                ContactsList.clear();
                qDebug("Contacts downloaded!");


                delete Stream;

                mNetworkCommSocket->write(GetTxPacket(SMS_CLIENT_DEVICE_GET_ALL_MSG_REQUEST,0,0,0,1,ID_MASTER,ID_SMS_CLIENT,mDeviceAddress));
                break;
            }
            case SMS_CLIENT_DEVICE_CONTACTS_CHANGED_NOTIFICATION:
            {
                mNetworkCommSocket->write(GetTxPacket(SMS_CLIENT_DEVICE_GET_CONTACTS_REQUEST,0,0,0,1,ID_MASTER,ID_SMS_CLIENT,mDeviceAddress));
                break;
            }

            case SMS_CLIENT_DEVICE_SEND_SMS_REQUEST:
            case SMS_CLIENT_DEVICE_STATUS_RESPONSE:
            case SMS_CLIENT_DEVICE_DID_INFO_REQUEST:
            case SMS_CLIENT_DEVICE_GET_ALL_MSG_REQUEST:
            default:
            {
                qDebug("SMSDevice: Invalid Ethernet MSg received: %d",MessageID);
                break;
            }

        }
    }

    return RET_OK;
}

//int CSMSMasterCtrlInterface::DisconnectMasterCtrl()
//{
//    if(mNetworkCommSocket != 0)
//    {
//        mNetworkCommSocket->close();
//      //  mNetworkCommSocket->deleteLater();
//    }

//    return RET_OK;
//}

//void CSMSMasterCtrlInterface::NetworkSocketConnected()
//{
//    qDebug("Connected to MasterCtrl");
//}

//void CSMSMasterCtrlInterface::NetworkSocketDataAvailable()
//{
//    AnalyzeRxBuffer(mNetworkCommSocket->readAll());
//}

void CSMSMasterCtrlInterface::SendSMS(CSMSMessage Message)
{
    QByteArray FrameData;
    QBuffer FrameBuffer(&FrameData);
    FrameBuffer.open(QIODevice::ReadWrite);
    QDataStream *FrameDataStrm = new QDataStream(&FrameBuffer);

    qint32 NbMsg = 1;

    *FrameDataStrm << NbMsg << Message;

    FrameBuffer.seek(0);

    mNetworkCommSocket->write(GetTxPacket(SMS_CLIENT_DEVICE_SEND_SMS_REQUEST,0,FrameData,FrameData.size(),1,ID_MASTER));

    FrameBuffer.close();
    delete FrameDataStrm;
}

//void CSMSMasterCtrlInterface::NetworkSocketDisconnected()
//{
//    qDebug("Disconnected from MasterCtrl");
////    delete mNetworkCommSocket;
////    mNetworkCommSocket = 0;
//}
