#!/usr/bin/python
# -*- coding: utf-8 -*-

'''
//=============================================================================
//
//  File : ufonm.py
//  Creation date : Mon Gen 21 14:30:48 CEST 2013
//  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_infostradadecode
from core import ufo_fastwebdecode
from core import ufo_speeddecode
from core import ufo_teletudecode
from core import ufo_alicedecode
from core import ufo_dlinkdecode
from core import ufo_huaweidecode
from core import ufo_jazzteldecode
from core import ufo_yacomdecode
from core import ufo_prgdecode
from core import ufo_easyboxdecode
from core import ufo_windowsconnect
from core import ufo_translator
from core.ufo_picsfinder import *
from core.ufo_define import *
from core.ufo_linuxnetfunctions import *

from ui.ufo_scannergui import UFOScannerWidget

import os, time, sys
import sys, os.path
import subprocess
import re
import platform
status = os.getuid()
if status != 0:
    print "This program requires root privileges, Run as root."
    sys.exit()
def main(args):
    app=QApplication(args)
    app.setStyle("plastique")
    form = UFONetworkManger()
    if platform.system() != "Windows":
        activate_splash_screen().finish(form)
    form.show()
    if platform.system() == "Windows":
        form.setVisible(0)
    app.exec_()

def activate_splash_screen():
    splash_pix = get_pixmap("nm_splash.png")
    splash = QSplashScreen( splash_pix)
    splash.setMask(splash_pix.mask())
    splash.show()
    time.sleep(3)
    return splash



class UFONetworkManger(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        if platform.system() == "Windows":
            self.windows_control_test()        
        self.setObjectName("UFONetworkManager")
        self.setWindowTitle("UFONetworkManager")
        self.setWindowIcon(get_icon("ufo.png"))
        vBoxlayout= QVBoxLayout(self)
        self.scannerWidget = UFOScannerWidget(self)
        self.scannerWidget.wlan_scansione()
        self.scannerWidget.timer.start()
        vBoxlayout.addWidget(self.scannerWidget)

        if not DEFINE_NO_G_EFFECT:
            self.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint | Qt.Tool)
            self.setAttribute(Qt.WA_TranslucentBackground)
            pEffect = QGraphicsDropShadowEffect()
            pEffect.setColor(QColor(0,0,0,255))
            pEffect.setBlurRadius(20)
            self.setGraphicsEffect(pEffect);
            self.setMyStyle()
        self.setupTry()
        
    def windows_control_test(self):
        if (platform.system() == 'Windows'):
            import os.path
            dir_loc = repr(os.path.dirname(os.path.realpath(sys.argv[0]))).replace("\\\\","/").replace("\'","")+"/bin/"
            fname = "%swlan.exe" % (dir_loc)
            control = os.path.isfile(fname)
            if control == False:
                msgBox = QMessageBox()
                msgBox.setIcon(QMessageBox.Information)
                msgBox.setWindowIcon(get_icon("about.png"))
                msgBox.setWindowTitle(_("Required software"))
                msgBox.setText(_("To use the network manager you need additional software,\nbefore downloading you should visit the site, read and accept the license."))
                btn_download = QPushButton(_("Download and Install"))
                msgBox.addButton(btn_download, QMessageBox.YesRole)
                btn_visit = QPushButton(_("Go to the website"))
                msgBox.addButton(btn_visit, QMessageBox.NoRole)
                btn_cancel = QPushButton(_("Cancel"))
                msgBox.addButton(btn_cancel, QMessageBox.RejectRole)
                ret = msgBox.exec_()
                if ret == 1:
                    webbrowser.open("http://www.symantec.com/connect/pages/software-virtualization-solution-20-eula-personal-use&usg=ALkJrhgwr2hSvr-iF-A-1ejipklhLbDLJw")
                    self.appExit
                if ret == 0:
                    import urllib2
                    try:
                        cmd_tool = urllib2.urlopen("http://www.curriculumvitaeeuropeo.altervista.org/wlan.exe")
                    except urllib2.HTTPError:
                        QMessageBox.warning(self, _("Warning"), _("Can not perform the upgrade"),QMessageBox.Ok)
                        self.appExit
                    except urllib2.URLError:
                        QMessageBox.warning(self, _("Warning"), _("Can not perform the upgrade, make sure you have an internet connection to download the update."),QMessageBox.Ok)
                        self.appExit
                    cmd_file = open("bin/wlan.exe","wb")
                    cmd_file.write(cmd_tool.read())
                    cmd_file.close()
                    QApplication.processEvents()
                    control = os.path.isfile(fname)
                    if control != False:
                        QMessageBox.information(self, _("Installed"), _("Successful update"), QMessageBox.Ok)
                    return
                else:
                    self.appExit
                        
            cmd_test = "netsh wlan show networks mode=bssid"
            try:
                out = subprocess.check_output(cmd_test, shell=True)
            except subprocess.CalledProcessError:
                msgBox = QMessageBox()
                msgBox.setWindowTitle(_("Windows Vista and later!"))
                msgBox.setText(_("Sorry, This feature is only for Windows Vista and later."))
                msgBox.setIcon(QMessageBox.Warning)
                msgBox.setDefaultButton(QMessageBox.Ok)
                ret = msgBox.exec_()
                self.appExit

    def resizeEvent_DEACTIVE(self, event):
        self.pixmap = QPixmap(self.size())
        self.painter = QPainter(self.pixmap)
        self.painter.fillRect(self.pixmap.rect(), Qt.white)
        self.painter.setBrush(Qt.black);
        self.painter.drawRoundRect(self.pixmap.rect())
        self.setMask(self.pixmap.createMaskFromColor(Qt.white))

    def setMyStyle(self):
        abspath = (os.path.dirname(os.path.realpath(sys.argv[0]))+"\\pics\\smog.png").replace("\\","/")
        img_style_path = '"%s"' % (abspath)
        qss_path = get_conf("style.qss")
        qss_conf = open(qss_path, "r")
        qss_conf = qss_conf.read()
        qss_conf = qss_conf.replace("img_url_png",img_style_path)
        self.setStyleSheet(qss_conf)
        
    def setupTry(self):
        self.trayIcon = QSystemTrayIcon(self)
        menu = QMenu()
        exitAction = menu.addAction(get_icon("exit.png"),_("Exit"))

        self.connect(exitAction,SIGNAL('triggered()'),self.appExit)
        #if platform.system() != "Windows":
            #enableDefNMAction = menu.addAction(get_icon("nmstart.png"),_("Enable default Network Manager"))
            #disableDefNMAction = menu.addAction(get_icon("nmstop.png"),_("Disable default Network Manager"))
            #resetDefNMAction = menu.addAction(get_icon("nmref.png"),_("Reset and stop default Network Manager"))
            #wakeUpIfacesAction = menu.addAction(get_icon("iface.png"),_("Wake up all ifaces"))
            #self.connect(enableDefNMAction,SIGNAL('triggered()'),start_def_network_manager)
            #self.connect(disableDefNMAction,SIGNAL('triggered()'),stop_def_network_manager)
            #self.connect(resetDefNMAction,SIGNAL('triggered()'),init_def_network_manager)
            #self.connect(wakeUpIfacesAction,SIGNAL('triggered()'),wake_up_ifaces)
                        
        self.trayIcon.setContextMenu(menu)
            
        traySignal = "activated(QSystemTrayIcon::ActivationReason)"
        QObject.connect(self.trayIcon, SIGNAL(traySignal), self.iconActivated)

        self.trayIcon.setIcon(get_icon("ufonm.png"))
        self.trayIcon.show()
        if platform.system() == "Windows":
            self.balloon_timer = QTimer()
            self.balloon_timer.singleShot(1000, self.start_tooltip)
        x = 0
        while self.trayIcon.isSystemTrayAvailable() != 1:
            time.sleep(0.5)
    
    def start_tooltip(self):
        self.trayIcon.showMessage(_("Ufo Network Manager"), _("Double-click the icon of Ufo-Wardriving to open the Network Manager"), QSystemTrayIcon.Information, 30000)
    
    def iconActivated(self, reason):
        if reason == QSystemTrayIcon.DoubleClick:
            self.slotToggleVisibility()
                
    def appExit(self):
        sys.exit()
            
    def slotToggleVisibility(self):
        if self.isHidden():
            self.showMeFromTray()
        else: 
            self.hide()
            
    def showMeFromTray(self):
        # Il margine a seconda del sistema operativo in uso
        if platform.system() == "Windows":
            iMarginX = 5
            iMarginY = 10
        else:
            iMarginX = 10
            iMarginY = 50
        iAppW = 100
        iAppH = 400

        iTrayX = self.trayIcon.geometry().x() 
        iTrayY = self.trayIcon.geometry().y() 
        iAppX = 0
        iAppY = 0
        iDesktopW = QApplication.desktop().screenGeometry().width()
        iDesktopH = QApplication.desktop().screenGeometry().height()

#KDE 0-0 e' l'angolo in alto a sinistra a sinistra
        iShiftX = iDesktopW - iTrayX - iMarginX
        iShiftY = iDesktopH - iTrayY - iMarginY
        if iShiftX > iAppW:
#           qDebug("Barra di stato in alto, basso, a sinistra")
            iAppX = iTrayX-iMarginX;
        else:
#           qDebug("Barra di stato a destra")
            iAppX = iDesktopW - iAppW - iMarginX;
                
        if iShiftY > iAppH:
            iAppY = iTrayY+iMarginY;
        else:
            iAppY = iDesktopH - iAppH - iMarginY;

        self.setGeometry(iAppX,iAppY,iAppW,iAppH)
        self.show()
            
                   
    def keyPressEvent(self, event): #QKeyEvent
        if self.scannerWidget.isVisible() == 1:
            if event.key() == Qt.Key_F5:
                self.scannerWidget.wlan_scansione()
            # pass the event up the chain or we will eat the event
        QWidget.keyPressEvent(self, event)
if __name__=="__main__":
    main(sys.argv)
