#!/usr/bin/python
#-*- coding=utf-8 -*-
import subprocess
import binascii
import time
import sys
import os
from PyQt4.QtCore import *
from PyQt4.QtGui import *
#from win32con import CREATE_NO_WINDOW 

abspath = os.path.dirname(os.path.realpath(sys.argv[0]))
localdir = abspath+"\\win_config\\"
dir_loc = abspath+"\\bin\\wlan.exe"

class WindowsConnectObj(QObject):
    def __init__(self, essid, auth, encr, key, guid, parent = None):
        super(WindowsConnectObj, self).__init__(parent=None)
        self.parent = parent
        #self.connect(self,SIGNAL("statusChanged"),self.printStatus)

    def wifi_profile(self, essid, xml_file, auth, encr, keytype, key ):
        essid_hex = binascii.b2a_hex(essid)
        xml_open = """<?xml version="1.0"?>
<WLANProfile xmlns="http://www.microsoft.com/networking/WLAN/profile/v1">
	<name>%s</name>
	<SSIDConfig>
		<SSID>
			<hex>%s</hex>
			<name>%s</name>
		</SSID>
	</SSIDConfig>
	<connectionType>ESS</connectionType>
	<connectionMode>auto</connectionMode>
	<MSM>
		<security>
			<authEncryption>
				<authentication>open</authentication>
				<encryption>none</encryption>
				<useOneX>false</useOneX>
			</authEncryption>
		</security>
	</MSM>
</WLANProfile>""" % (essid, essid_hex.upper(), essid)

        xml = """<?xml version="1.0"?>
<WLANProfile xmlns="http://www.microsoft.com/networking/WLAN/profile/v1">
    <name>%s</name>
    <SSIDConfig>
        <SSID>
            <hex>%s</hex>
            <name>%s</name>
        </SSID>
    </SSIDConfig>
    <connectionType>ESS</connectionType>
    <connectionMode>auto</connectionMode>
    <MSM>
        <security>
            <authEncryption>
                <authentication>%s</authentication>
                <encryption>%s</encryption>
                <useOneX>false</useOneX>
            </authEncryption>
            <sharedKey>
                <keyType>%s</keyType>
                <protected>false</protected>
                <keyMaterial>%s</keyMaterial>
            </sharedKey>
        </security>
    </MSM>
</WLANProfile>"""  % (essid, essid_hex.upper(), essid, auth, encr, keytype, key)
        with open(xml_file, "w") as f:
            if auth == "open" and encr == "none":
                f.write(xml_open)
            else:
                f.write(xml)
            f.close()


    def wifi_add_profile(self, guid, xml_file):
        out = subprocess.Popen([dir_loc, "sp", guid, xml_file], stdout=subprocess.PIPE, creationflags=CREATE_NO_WINDOW)
        output = out.stdout.read()

    def wifi_del_profile(self, guid, essid):
        out = subprocess.Popen([dir_loc, "dp", guid, essid], stdout=subprocess.PIPE, creationflags=CREATE_NO_WINDOW)
        output = out.stdout.read()

    def configure_and_connect(self, essid, auth, encr, key, guid, keytype):
        self.wifi_disconnect(guid)
        self.wifi_del_profile(guid, essid)
        xml_file = "%s.xml" % (essid)
        xml_file = localdir+"/"+xml_file
        xmlprofile = self.wifi_profile(essid, xml_file, auth, encr, keytype, key)
        addprofile = self.wifi_add_profile(guid, xml_file)
        connect = self.wifi_connect(essid, guid)
        if not connect:
            self.wifi_del_profile(guid, essid)  
            QApplication.processEvents()
            return False
        if connect:
            return True
        
    def wifi_try_connect(self, essid, auth, encr, key, guid):
        if "WPA" in auth:
            keytype = "passPhrase"
        else:
            keytype = "NetworkKey"
        if key == False:
            return False
        if type(key) == list:
            for wifikey in key:
                connection = self.configure_and_connect(essid, auth, encr, wifikey, guid, keytype)
                if connection == True:
                    return True
                else:
                    connection = self.configure_and_connect(essid, auth, encr, wifikey, guid, keytype)
            return connection
        if key == "":
            keytype = ""
            connection = self.configure_and_connect(essid, auth, encr, key, guid, keytype)
            return connection

    def wifi_disconnect(self, guid):
        out = subprocess.Popen([dir_loc, "dc", guid], stdout=subprocess.PIPE, creationflags=CREATE_NO_WINDOW)
        output = out.stdout.read()
        
            
                

    def get_wifi_interfaces(self):
        out = subprocess.Popen([dir_loc, "ei"], stdout=subprocess.PIPE, creationflags=CREATE_NO_WINDOW)
        output = QString(out.stdout.read())
        interfacelist = output.split(QRegExp("[^B]Interface"))
        cellsnumber = interfacelist.count()
        interface = 1
        netlist = {}
        while interface != cellsnumber:
            infocellist = QStringList
            infocelllist =interfacelist[interface].split("\n")
            guid = " ".join(str(infocelllist[1].section(":",1,-1)).split())
            scheda = " ".join(str(infocelllist[2]).split())
            stato = " ".join(str(infocelllist[3].section(":",1,-1)).replace('"',"").split())
            interface = interface+1
            netlist[guid] = [guid, scheda, stato]
        return netlist


    def wifi_connect(self, essid, guid):
        out = subprocess.Popen([dir_loc, "conn", guid, essid, "i", essid], stdout=subprocess.PIPE, creationflags=CREATE_NO_WINDOW)
        output = out.stdout.read()
        info = self.get_wifi_interfaces()
        try:
            status = info[guid][2]
            a = 0
        except KeyError:
            a = 1
        if a == 0:
            b = 0
            while True:
                if status in ["authenticating", "associating", "disconnecting"]:
                    info = self.get_wifi_interfaces()
                    status = info[guid][2]
                    QApplication.processEvents()
                if status == "disconnected":
                    return False
                if status == "connected":
                    return True
        #wifi_try_connect("Lineafastweb00", "Lineafastweb00.xml", "WPAPSK", "TKIP", "Password","f38a7be0-fd4c-4e1e-834d-d1c15a322048")
            
            
