#!/usr/bin/python
'''
//=============================================================================
//
//  File : ufo_scannerguy.py
//  Creation date : Wed Dec 05 14:30:48 CEST 2012
//  Working on this file:   asterix (Cristian Steri)
//                          Grifisx (Antonino G. Imbesi)
//   This file is part of the Ufo Wardriving distribution
//
//  Websites: http://ufo-wardriving.com
//
//   This program is FREE software. You can redistribute it and/or
//   modify it under the terms of the GNU General Public License
//   as published by the Free Software Foundation; either version 2
//   of the License, or (at your opinion) any later version.
//
//  This program is distributed in the HOPE that it will be USEFUL,
//   but WITHOUT ANY WARRANTY; without even the implied warranty of
//   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
//   See the GNU General Public License for more details.
//
//   You should have received a copy of the GNU General Public License
//   along with this program. If not, write to the Free Software Foundation,
//   Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
//=============================================================================
'''

from PyQt4.QtCore import *
from PyQt4.QtGui import *

from core import ufo_linuxscanner
from core import ufo_windows_scanner
from core.ufo_define import *
from core.ufo_picsfinder import *

from ui.ufo_iconlabel import UFOIconLabel
from ui.ufo_scanelement import *
from ui.ufo_scanlistwidget import *

import os
import sys
import os.path
import subprocess
import re
import platform

class UFOScannerWidget(QWidget):
    def __init__(self, parent=None):
        super(UFOScannerWidget, self).__init__(parent)
        self.parent = parent
        self.timerEnabled = True
        self.setToolTip(_("Hit F5 to refresh"))
        if platform.system() == "Windows":
            self.timer = QTimer(self)
            self.timer.setInterval(15000)
        else:
            self.timer = QTimer(self)
            self.timer.setInterval(6000)
        hBoxLayout = QHBoxLayout()
        hBoxLayout.setSpacing(5)
        
        vBoxLayout = QVBoxLayout()
        vBoxLayout.setSpacing(1)

        if self.parent.objectName() == "UFOMainWidget":
            self.scannerLabel = QLabel("<b>Wifi Scanner</b>")
            self.scannerLabel.setAlignment(Qt.AlignCenter)
            self.scannerLabel.setObjectName("UFOScannerLabel")
        else:
            if not DEFINE_NO_G_EFFECT:
                self.ufoLabel = QLabel(self)
                self.ufoLabel.setObjectName("UFOLabel")
                self.ufoLabel.setFixedSize(QSize(40,40))
                self.ufoLabel.setPixmap(get_pixmap("ufooo.png"))
                
            self.scannerLabel = QLabel("<b>UFO Network Manager</b>")
            self.scannerLabel.setObjectName("UFOScannerLabel")
            self.stateLabel = UFOIconLabel(self)
            self.stateLabel.setLabelWidgetName("UFOStateLabel")
            self.stateLabel.setLabelTextName("UFOStateLabelText")
            self.stateLabel.setLabelPixmapName("UFOStateLabelPixmap")
            
        self.outputListWi = UFOScannListWidget(self)

        hBoxLayout.addWidget(self.scannerLabel)
        if self.parent.objectName() == "UFOMainWidget":
            vBoxLayout.addLayout(hBoxLayout)
            vBoxLayout.addWidget(self.outputListWi)
            #if (platform.system() != 'Windows'):
            self.stateLabel = UFOIconLabel()
            vBoxLayout.addWidget(self.stateLabel)
        else:
            if not DEFINE_NO_G_EFFECT:
                vBoxLayout.addWidget(self.ufoLabel)
            vBoxLayout.setAlignment(Qt.AlignLeft)
            vBoxLayout.addLayout(hBoxLayout)
            vBoxLayout.addWidget(self.outputListWi)
            vBoxLayout.addWidget(self.stateLabel)

        self.setLayout(vBoxLayout)
        self.timer.timeout.connect(self.wlan_scansione)
        
        def find_item():
            item = self.outputListWi.currentItem()
            if item.text().startsWith("Fastweb-1"):
                parent.UFOFastWidget.macLineEdit.setText(item.text().trimmed().right(12))
                parent.UFOFastWidget.find_key()
                parent.tabWidget.setCurrentIndex(0)

            if item.text().startsWith("Thomson") or item.text().startsWith("INFINITUM") or item.text().startsWith("SpeedTouch") or item.text().startsWith("O2Wireless") or item.text().startsWith("Orange-") or item.text().startsWith("BigPond") or item.text().startsWith("Otenet") or item.text().startsWith("Bbox-") or item.text().startsWith("DMAX") or item.text().startsWith("privat"):
                parent.UFOSpeedWidget.ssidLineEdit.setText(item.text().trimmed().right(6))
                parent.UFOSpeedWidget.find_key()
                parent.tabWidget.setCurrentIndex(1)
                
            if item.text().startsWith("BTHomeHub"):
                parent.UFOSpeedWidget.ssidLineEdit.setText(item.text().trimmed().right(4))
                parent.UFOSpeedWidget.find_key()
                parent.tabWidget.setCurrentIndex(1)

            if item.text().startsWith("TeleTu_") or item.text().startsWith("Tele2"):
                parent.UFOTeletuWidget.lineEditTeletu.setText(item.get_mac())
                parent.UFOTeletuWidget.find_key()
                parent.tabWidget.setCurrentIndex(2)

            if item.text().startsWith("PBS-"):
                parent.UFOPrgWidget.lineEditprg.setText(item.get_mac())
                parent.UFOPrgGui.find_key()
                parent.tabWidget.setCurrentIndex(9)
                
            if item.text().startsWith("EasyBox-") or item.text().startsWith("Vodafone-") or item.text().startsWith("Arcor-"):
                parent.UFOEasyboxWidget.lineEditeasybox.setText(item.get_mac())
                parent.UFOEasyboxWidget.find_key()
                parent.tabWidget.setCurrentIndex(10)

            if item.text().startsWith("Discus-") or item.text().startsWith("Discus--"):
                parent.UFODiscusWidget.ssidLineEdit.setText(item.text().trimmed().right(6))
                parent.UFODiscusWidget.find_key()
                parent.tabWidget.setCurrentIndex(11)
                
            if item.text().startsWith("Infostrada-"):
                parent.UFOInfostradaWidget.macLineEdit.setText(item.get_mac())
                parent.UFOInfostradaWidget.find_key()
                parent.tabWidget.setCurrentIndex(3)

            if item.text().startsWith("Alice-"):
                parent.UFOAliceWidget.ssidLineEdit.setText(item.text().trimmed().right(8))
                parent.UFOAliceWidget.macLineEdit.setText(item.get_mac())
                parent.UFOAliceWidget.find_key()
                parent.tabWidget.setCurrentIndex(4)

            if item.text().startsWith("Dlink-"):
                parent.UFODLinkWidget.inputMacLineEdit.setText(item.get_mac())
                parent.UFODLinkWidget.find_key()
                parent.tabWidget.setCurrentIndex(5)

            if item.text().startsWith("Huawei-"):
                parent.UFOHuaweiWidget.macLineEdit.setText(item.get_mac())
                parent.UFOHuaweiWidget.find_key()
                parent.tabWidget.setCurrentIndex(6)

            if item.text().startsWith("JAZZTEL_") or item.text().startsWith("WLAN_"):
                parent.UFOJazztelWidget.ssidLineEdit.setText(item.text().trimmed().right(4))
                parent.UFOJazztelWidget.macLineEdit.setText(item.get_mac())
                parent.UFOJazztelWidget.find_key()
                parent.tabWidget.setCurrentIndex(7)

            if item.text().startsWith("YaCom") or item.text().startsWith("WLAN"):
                parent.UFOYacomWidget.ssidInputLineEdit.setText(item.text().trimmed().right(6))
                parent.UFOYacomWidget.macInputLineEdit.setText(item.get_mac())
                parent.UFOYacomWidget.find_key()
                parent.tabWidget.setCurrentIndex(8)
        if self.parent.objectName() == "UFOMainWidget":
            self.outputListWi.itemDoubleClicked.connect(find_item)
            
    def wlan_scansione(self):
        if (platform.system() == 'Windows'):
            self.outputListWi.clear()
            netlist = ufo_windows_scanner.wlan_scanner()
            tmpiface = ""
            idx = 0
            f = QFont()
            f.setItalic(1)
            iteration_bssid = 0
            iteration_ssid = 0
            for interface in netlist:
                if interface != tmpiface:
                    ifaceitem = UFOScannViewElement(self.outputListWi)
                    ifaceitem.setFont(f)
                    ifaceitem.set_ifaceFlag(True)
                    ifaceitem.setTextAlignment(Qt.AlignCenter)
                    ifaceitem.setBackground(QColor(205,186,150))
                    ifaceitem.setText(interface)
                    tmpiface = interface
                    self.outputListWi.insertItem(idx,ifaceitem)
                    idx = idx + 1
                for ssid in netlist[interface]:
                    net_essid = ssid
                    #print net_essid
                    for bssid in netlist[interface][ssid]["bssid"]:
                        net_mac = bssid
                        item = UFOScannViewElement(self.outputListWi)
                        item.set_iface(ufo_windows_scanner.get_interface_info(interface))
                        item.set_mac(net_mac)
                        for info in netlist[interface][ssid]["bssid"][bssid]:
                            iteration_bssid = iteration_bssid+1
                            if iteration_bssid == 1:
                                net_signal = netlist[interface][ssid]["bssid"][bssid][info]
                                #print net_signal
                                item.set_signal(net_signal)
                            if iteration_bssid == 3:
                                net_chan = netlist[interface][ssid]["bssid"][bssid][info]
                                #print net_chan
                                item.set_channel(net_chan)
                            if iteration_bssid == 4:
                                net_freq = netlist[interface][ssid]["bssid"][bssid][info]
                                #print net_freq
                                item.set_frequency(net_freq)
                            if iteration_bssid == 5:
                                iteration_bssid = 0
                        for info in netlist[interface][ssid]:
                            iteration_ssid = iteration_ssid+1
                            if iteration_ssid == 1:
                                net_auth = netlist[interface][ssid][info]
                                #print net_auth
                            if iteration_ssid == 3:
                                net_cifr = netlist[interface][ssid][info]
                                #print net_cifr
                            if iteration_ssid == 4:
                                iteration_ssid = 0  
                                if net_auth == "WPA-Personal":
                                    net_auth = "WPAPSK"
                                elif net_auth == "WPA2-Personal":
                                    net_auth = "WPA2PSK"
                
                                elif net_auth == "WPA2-Enterprise":
                                    net_auth = "WPA2"
                                elif net_auth == "WPA-Enterprise":
                                    net_auth = "WPA"
                                else:
                                    net_auth = "open"
                                if "WEP" not in net_cifr and net_cifr != "CCMP" and net_cifr != "TKIP":
                                    net_cifr = "none"
                                else:
                                    if net_cifr == "CCMP":
                                        net_cifr = "AES"
                                    if "WEP" in net_cifr:
                                        net_cifr = "WEP"
                    
                                item.set_encription(net_auth)
                                item.set_encription2(net_cifr)         
                        if net_essid:
                            item.set_ssid(net_essid)
                        else:
                            item.set_ssid("-Hidden-")
                        self.outputListWi.insertItem(idx,item) 
                        item.set_signal_icon(net_signal) 
                        item.set_win_info()
                        item = ""
                        item = UFOScannViewElement(self.outputListWi)
                        idx = idx+1
                        QApplication.processEvents()
        else:
            ifacelist = ufo_linuxscanner.get_iface_list()
            aplist = ufo_linuxscanner.get_ap_list()
            tmpiface = ""
            self.outputListWi.clear()
            idx=0
            f = QFont()
            f.setItalic(1)
            for ap in aplist:
                if ap.get_iface() !=tmpiface:
                    ifaceitem = UFOScannViewElement(self.outputListWi)
                    ifaceitem.setFont(f)
                    ifaceitem.set_ifaceFlag(True)
                    ifaceitem.setTextAlignment(Qt.AlignCenter)
                    ifaceitem.setBackground(QColor(205,186,150))
                    ifaceitem.setText(ap.get_iface())
                    tmpiface =ap.get_iface()
                    self.outputListWi.insertItem(idx,ifaceitem)
                    idx=idx+1
                item = UFOScannViewElement(self.outputListWi)
                item.set_ssid(ap.get_essid())
                item.set_mac(ap.get_mac())
                item.set_signal(ap.get_signal_percentage())
                item.set_frequency(ap.get_freq())
                item.set_encription(ap.get_encr())
                item.set_dbm_value(ap.get_signal_percentage())
                item.set_iface(ap.get_iface())
                item.set_info()
                self.outputListWi.insertItem(idx,item)
                idx = idx+1


    def wake_up_ifaces(self):
        l=ufo_linuxscanner.get_iface_list()
        for i in l:
            if i !="":
                subprocess.call(["ifconfig",self.iface,"down"])
                subprocess.call(["ifconfig",self.iface,"up"])
                subprocess.call(["iwlist", i, "scanning"])

