#coding:utf-8
'''
Created on Sep 3, 2014

@author: root
'''
import os

from PyQt4.QtCore import SIGNAL
from PyQt4.QtGui import QGridLayout
from PyQt4.QtGui import QGroupBox
from PyQt4.QtGui import QLineEdit, QRadioButton
from PyQt4.QtGui import QPushButton
from PyQt4.QtGui import QWidget, QLabel, QHBoxLayout, QVBoxLayout

from base.infohintdialog import InfoHintDialog
from base.storeinfoparser import StoreInfoParser
import setting.globalfunc
from setting.logrecord import LogRecord
from setting.waitdlg import WaitingWidget
from wirelessinfo import WireCtl


class WirelessNetworkSetting(QWidget):
       
    def __init__(self,parent = None):
        super(WirelessNetworkSetting,self).__init__(parent)
        
        self.wireCtl = WireCtl()
        self.waitDlg = WaitingWidget()
        self.radioButton_G = QRadioButton()
        self.radioButton_G.setText(u"3G网卡")
        
        self.radioButton_W = QRadioButton()
        self.radioButton_W.setText(u"WiFi")
        
        self.wifiSetting = QGroupBox()
        self.wifiSetting.setTitle(u"WiFi设置")
        
        self.idLabel = QLabel(u"ID")
        self.idLabel.setFixedWidth(80)
        self.userNameLabel = QLabel(u"用户名")
        self.userNameLabel.setFixedWidth(80)
        self.passwdLabel = QLabel(u"密码")
        self.passwdLabel.setFixedWidth(80)
        
        self.lineEditId = QLineEdit()
        #self.lineEditId.setFixedWidth(300)
        self.lineEditUserName = QLineEdit()
        #self.lineEditUserName.setFixedWidth(300)
        self.lineEditPasswd = QLineEdit()
        self.lineEditPasswd.setEchoMode(QLineEdit.Password)
        #self.lineEditPasswd.setFixedWidth(300)
        
        self.start_GButton = QPushButton(u"启用")
        self.start_GButton.setObjectName("settingDlgBtn")
        self.start_GButton.setFixedSize(100,31)
        self.start_GButton.setStyleSheet("QPushButton{background:lightgray;}"
                                         "QPushButton{color: black; font: 10pt; border:1px groove gray;padding:2px 4px;}"
                                         "QPushButton::hover{color: black; font: 10pt; border:1px groove lightblue;padding:2px 4px;}")
        self.saveButton = QPushButton(u"保存")
        self.saveButton.setObjectName("settingDlgBtn")
        self.saveButton.setFixedSize(75,27)
        self.saveButton.setFlat(True)
        self.closeButton = QPushButton(u"关闭")
        self.closeButton.setObjectName("settingDlgBtn")
        self.closeButton.setFixedSize(75,27)
        self.closeButton.setFlat(True)
        
        saveButtonLayout = QHBoxLayout()
        saveButtonLayout.setMargin(20)
        saveButtonLayout.addStretch()
        saveButtonLayout.addWidget(self.saveButton)
        saveButtonLayout.addStretch()
        
        groupLayout = QGridLayout()
        #groupLayout.setMargin(40)
        groupLayout.addWidget(self.idLabel,0,0,1,1)
        groupLayout.addWidget(self.lineEditId,0,1,1,1)
        groupLayout.addWidget(self.userNameLabel,1,0,1,1)
        groupLayout.addWidget(self.lineEditUserName,1,1,1,1)
        groupLayout.addWidget(self.passwdLabel,2,0,1,1)
        groupLayout.addWidget(self.lineEditPasswd,2,1,1,1)
        groupLayout.addLayout(saveButtonLayout,3,0,1,2)
        myGroupLayout = QHBoxLayout()
        myGroupLayout.addSpacing(80)
        myGroupLayout.addLayout(groupLayout)
        myGroupLayout.addSpacing(80)
        
        self.wifiSetting.setLayout(myGroupLayout)
        
        
        gLayout = QHBoxLayout()
        gLayout.addWidget(self.radioButton_G)
        gLayout.addWidget(self.start_GButton)
        gLayout.addStretch()
        
        closeButtonLayout = QHBoxLayout()
        closeButtonLayout.addStretch()
        closeButtonLayout.addWidget(self.closeButton)
        
        miniWidget = QWidget()
        miniLayout = QVBoxLayout(self)
        miniLayout.setMargin(50)
        miniLayout.addLayout(gLayout)
        miniLayout.addSpacing(20)
        miniLayout.addWidget(self.radioButton_W)
        miniLayout.addSpacing(20)
        miniLayout.addWidget(self.wifiSetting)
        miniLayout.addSpacing(40)
        miniLayout.addLayout(closeButtonLayout)
        miniWidget.setLayout(miniLayout)
        
        self.mainLayout = QHBoxLayout(self)
        self.mainLayout.addSpacing(30)
        self.mainLayout.addWidget(miniWidget)
        self.mainLayout.addSpacing(30)
        
        self.wire_open = u"开启无线网卡"
        self.wire_close = u"禁用无线网卡"
        
        self.start_GButton.setToolTip(u"注意：开启3Ｇ网卡会禁用有线网络，所以当3Ｇ网卡使用完毕时请'禁用无线网卡'")
        
        self.refreshWidget()
        
        
        
        
        self.connect(self.closeButton, SIGNAL("clicked()"),self.closeTabWidget)
        self.connect(self.start_GButton,SIGNAL("clicked()"),self.on_pushButton_3G_clicked)
        self.connect(self.wireCtl, SIGNAL("wireSuccess"),self.wireOpenSuccess)
        self.connect(self.wireCtl, SIGNAL("wireFaild"),self.wireOpenFaild)
        self.connect(self.wireCtl, SIGNAL("noWireNet"),self.noWire)
        self.connect(self.wireCtl, SIGNAL("closeWireSuccess"),self.wireCloseSuccess)
        self.connect(self.wireCtl, SIGNAL("closeWireFiald"),self.wireCloseFaild)
        self.connect(self.saveButton, SIGNAL("clicked()"),self.slotSaveWifi)
    def slotSaveWifi(self):
        userName = self.lineEditUserName.text()
        passWd = self.lineEditPasswd.text()
        lineFirst = "network={"
        lineSecond = "ssid='" + userName + "'"
        lineThree = "psk='" + passWd + "'"
        lineFour = "#psk=c0f293f6e1c21bd99d5764a565f9708e187da6972bc96dc5f1c69a35211a3116}"
        
        path = "/etc/wpa_supplicant/wpa_supplicant.conf"
        
        cmd1 = "echo " + lineFirst + ">>" + path
        cmd2 = "echo " + lineSecond + ">>" + path
        cmd3 = "echo " + lineThree + ">>" + path
        cmd4 = "echo " + lineFour + ">>" + path
        
        os.system(str(cmd1))
        os.system(str(cmd2))
        os.system(str(cmd3))
        os.system(str(cmd4))
        
        os.system("wpa_supplicant -Dwext -iwlan0 -c/etc/wpa_supplicant.conf")
        
        InfoHintDialog(u"wifi设置成功！").exec_()
        
    def refreshWidget(self):
        LogRecord.instance().logger.info(u"判断无线网卡是否启用，初始化按钮")
        if (os.system("grep -q 'rdnis_host' /proc/modules")):
            self.start_GButton.setText(self.wire_open)
        else:
            self.start_GButton.setText(self.wire_close)
            

        LogRecord.instance().logger.info(u"读取文件中无线网卡设置，初始化窗口状态")
        wireNetStatus=StoreInfoParser.instance().getWirelessNetwork()
        #file.close()
        if wireNetStatus == "close":
            self.start_GButton.setEnabled(True)
            self.radioButton_G.setEnabled(True)
            self.radioButton_G.setChecked(True)
            
            self.radioButton_W.setEnabled(False)
            self.wifiSetting.setEnabled(False)
        elif wireNetStatus == "open":
            self.start_GButton.setEnabled(False)
            self.radioButton_G.setEnabled(False)
            
            self.radioButton_W.setEnabled(True)
            self.wifiSetting.setEnabled(True)
        else:
            self.start_GButton.setEnabled(True)
            self.radioButton_G.setEnabled(True)
            self.radioButton_G.setChecked(True)
            self.radioButton_W.setEnabled(False)
            self.wifiSetting.setEnabled(False)
            
        
    def on_pushButton_3G_clicked(self):
        LogRecord.instance().logger.info(u"开启无线网卡按钮点击")
        LogRecord.instance().logger.info(u"禁用无线网卡按钮点击")
        btn_statu = u"检测3G网卡"
        if self.start_GButton.text() == u"开启无线网卡":
            self.start_GButton.setText(btn_statu)
            self.start_GButton.setEnabled(False)
            LogRecord.instance().logger.info(u"开启线程，打开无线网卡")
            self.wireCtl.start()
            
            self.waitDlg.setTip(u"打开无线中...")
            self.waitDlg.show()
            self.waitDlg.move(setting.globalfunc.moveToCenter(self.waitDlg.width(), self.waitDlg.height()))
        else:
            self.start_GButton.setText(btn_statu)
            self.start_GButton.setEnabled(False)
            LogRecord.instance().logger.info(u"开启线程，打开无线网卡")
            self.wireCtl.start()
            self.waitDlg.setTip(u"关闭无线中...")
            self.waitDlg.show()
            self.waitDlg.move(setting.globalfunc.moveToCenter(self.waitDlg.width(), self.waitDlg.height()))
        #wireNet状态检测
    def wireOpenSuccess(self):
        self.waitDlg.close()
        self.start_GButton.setEnabled(True)
        self.start_GButton.setText(self.wire_close)
        #QMessageBox.information(self,u"信息",u"开启3Ｇ网卡成功")
        InfoHintDialog(u"开启无线网卡成功！").exec_()
        
        self.wifiSetting.setEnabled(True)
        
    def wireOpenFaild(self):
        self.waitDlg.close()
        self.start_GButton.setEnabled(True)
        self.start_GButton.setText(self.wire_open)
        #QMessageBox.information(self,u"错误",u"开启3Ｇ网卡失败，请重试")
        InfoHintDialog(u"开启3Ｇ网卡失败，请重试").exec_()
    
    def noWire(self):
        self.waitDlg.close()
        
        self.start_GButton.setEnabled(True)
        self.start_GButton.setText(self.wire_open)
        #QMessageBox.information(self,u"错误",u"没有检测到3G网卡，请重试")
        InfoHintDialog(u"没有检测到3G网卡，请重试").exec_()
    
    def wireCloseSuccess(self):
        self.waitDlg.close()
        self.start_GButton.setEnabled(True)
        self.start_GButton.setText(self.wire_open)
        #QMessageBox.information(self,u"信息",u"禁用3Ｇ网卡成功")
        InfoHintDialog(u"禁用3Ｇ网卡成功").exec_()
    def wireCloseFaild(self):
        
        self.start_GButton.setEnabled(True)
        self.start_GButton.setText(self.wire_open)
        #QMessageBox.information(self,u"错误",u"禁用3Ｇ网卡失败，请重试")
        InfoHintDialog(u"禁用3Ｇ网卡失败，请重试").exec_()
    
    def closeTabWidget(self):
        self.emit(SIGNAL("closetabwidget"))

if __name__ == "__main__":

    from PyQt4 import QtGui
    import sys
    app = QtGui.QApplication(sys.argv)
    window = WirelessNetworkSetting()
    window.show()
    app.exec_()
