#include "NetworkCfgMgr.h"
#include <QFile>
#include <QTextStream>
#include "ZTLog.h"

CNetworkCfgMgr::CNetworkCfgMgr()
{
}

int CNetworkCfgMgr::SetTRCPNetworkAddress(QHostAddress Address)
{
    //Verify if the template file exists
    if(QFile::exists("./interfaces") == false)
    {
        CZTLog::instance()->AddLogString("ERREUR: Le fichier template de configuration réseau est inexistant",true);
        return RET_ERROR;
    }

    //Open the template file
    QFile *TemplateFile = new QFile("./interfaces");
    if(TemplateFile)
    {
        if(TemplateFile->open(QIODevice::ReadOnly | QIODevice::Unbuffered | QIODevice::Text) == false)
        {
            CZTLog::instance()->AddLogString("ERREUR: impossible d'ouvrir le fichier template de configuration réseau",true);
            delete TemplateFile;
            return RET_ERROR;
        }


    }
    else
    {
        CZTLog::instance()->AddLogString("ERREUR: impossible d'ouvrir le fichier template de configuration réseau",true);
        return RET_ERROR;
    }


    //Create a temporary file
    QFile *TempInterfaceFile = new QFile("./interfaces_tmp");
    if(TempInterfaceFile)
    {
        if(TempInterfaceFile->open(QIODevice::WriteOnly | QIODevice::Truncate | QIODevice::Text | QIODevice::Unbuffered) == false)
        {
            CZTLog::instance()->AddLogString("ERREUR: impossible de créer le fichier temporaire de configuration réseau",true);
            delete TempInterfaceFile;
            return RET_ERROR;
        }

    }
    else
    {
        CZTLog::instance()->AddLogString("ERREUR: impossible de créer le fichier temporaire de configuration réseau",true);
        return RET_ERROR;
    }

    QString ConfigText(TemplateFile->readAll());
    QString WorkString;

    //Compute the gateway address as xxx.xxx.xxx.1
    quint32 GatewayTemp = (Address.toIPv4Address() & 0xFFFFFF00);
    GatewayTemp |= 0x00000001;
    QHostAddress Gateway(GatewayTemp);

    WorkString = ConfigText.replace("[TELETRANS_IP]",Address.toString());
    ConfigText = WorkString.replace("[TELETRANS_GATEWAY]",Gateway.toString());

    if(TempInterfaceFile->write(ConfigText.toAscii()) < 0)
    {
        CZTLog::instance()->AddLogString("ERREUR: impossible de créer le fichier temporaire de configuration réseau",true);
    }

    TemplateFile->close();
    delete TemplateFile;

    TempInterfaceFile->close();
    delete TempInterfaceFile;


    //Replace the system file with the temp file.
    system("cp -f ./interfaces_tmp /etc/network/interfaces");

    CZTLog::instance()->AddLogString(QString("Changement de l'adresse IP: %1").arg(Address.toString()),true);


    return RET_OK;

}
