#include "modulewifi.h"

#include <QDebug>
#include <cstdlib>
#include <QFile>


ModuleWifi::ModuleWifi(QObject *parent) : QObject(parent)
{
    pWifi = new WifiDisConnected();
    state = false;
    QTimer::singleShot(1000, this, SLOT(onTimerTimeOutCheck()));
}

ModuleWifi::~ModuleWifi()
{
    qDebug("~ModuleWifi");
    delete pWifi;
}

bool ModuleWifi::isConnected()
{
    return pWifi->state();
}

int ModuleWifi::getquality()
{
    int wifiquality;
    wifiquality = pWifi->quality();
    return wifiquality;
}

void ModuleWifi::onConnect(QString name, QString passwd)
{
    if(this->name == name && this->passwd == passwd){
        if(pWifi->state()){
            return;
        }
    }

    this->name =  name ;
    this->passwd = passwd;
    delete pWifi;
    pWifi = new WifiConnecting();
    pWifi->connect(name, passwd);
}

void ModuleWifi::onDisconnect()
{
    qDebug("onDisconnect");
    if(!pWifi->state()){
        return;
    }

    delete pWifi;
    pWifi = new WifiDisConnected();
    pWifi->disconnect();
}

void ModuleWifi::onTimerTimeOutCheck()
{
    pWifi = pWifi->run(pWifi);
    if(pWifi->state() != state){
        state = pWifi->state();
        emit sigStateChanged(state);
    }

    QTimer::singleShot(1000, this, SLOT(onTimerTimeOutCheck()));
}

WifiBase* WifiDisConnected::run(WifiBase* p)
{
    qDebug("WifiDisConnected::run");
    return p;
}

WifiBase* WifiConnecting::run(WifiBase* p)
{
    qDebug("WifiConnecting::run");
    if(connectCheck()){
        delete p;
        p = new WifiConnected();
    }
    return p;
}

WifiBase* WifiConnected::run(WifiBase* p)
{
    qDebug("WifiConnected::run");
    if(!connectCheck()){
        delete p;
        p = new WifiDisConnected();
    }
    return p;
}

void WifiBase::connect(QString name, QString passwd)
{
    //TODO: 连接WIFI
    qDebug() << QString("connect: %1, %2").arg(name).arg(passwd);
    /*wifi连接*/
    std::system("timeout 12s nohup /usr/sbin/wpa_supplicant -Dnl80211 -imlan0 -c /etc/sta.conf -B");
    std::system("udhcpc -i mlan0 &");
}

void WifiBase::disconnect()
{
    //TODO:断开WIFI
    qDebug("disconnect");
    std::system("killall wpa_supplicant");
}

bool WifiBase::connectCheck()
{

    QString wifi_quality;
    bool rtn = false;

    std::system("iwconfig mlan0 | grep -i quality >/home/data/wlxx_wifi_quality");
    QFile file_read("/home/data/wlxx_wifi_quality");
    if(file_read.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        QTextStream in(&file_read);//创建一个对象让它去读文件
        QString line_wifi_quality=in.readLine();
        wifi_quality = line_wifi_quality.mid(23, 1);//获取质量

        if((wifi_quality=="0")|(wifi_quality==""))//WIFI断网
        {
            quality_val = 0;
            rtn =  false;
        }
        else
        {
            quality_val = wifi_quality.toInt();
            rtn =  true;
        }
    }

    file_read.close();
    return rtn;
}

int WifiBase::quality()
{
    return quality_val;
}
