class baseFunc:
    """基本功能类"""

    #----------------------------------------------------------------------
    def __init__(self):
        """Constructor"""
        self.common_fn = CommonFunctions()
        
    #----------------------------------------------------------------------
    def uninstallAPP(self,name):
        """卸载指定应用"""
        isHome = False
        while not isHome:
            self.common_fn.driver.keyevent('4')
            time.sleep(2)
            if self.common_fn.driver.current_activity == '.activity.MarketHomeActivity':
                isHome = True
        print 'uninstall app'
        time.sleep(5)
        tabs = self.common_fn.com_find_element(r'android:id/tabs')
        tabs.find_element(By.NAME,u'管理').click()
        action_buttons=self.common_fn.wait_for_elements(r'com.tclmarket:id/manage_image',By.ID)
        action_texts=self.common_fn.wait_for_elements(r'com.tclmarket:id/manage_text',By.ID)
        if action_texts[2].text==u'已安装' :
            action_buttons[2].click()
            time.sleep(2)
            print u'get installed apks page\n'
            self.findByName(name)
        else:   
            print u'not get installed apks page\n'
            return False        

            #print self.common_fn.com_find_element(name,By.NAME)

        #----------------------------------------------------------------------
    def findByName(self,name):
        """查找指定应用列表"""
        try:
            isLast = False
            lastAPP = ''
            while not isLast:
                apps = self.common_fn.wait_for_elements(r'android.widget.RelativeLayout',By.CLASS_NAME)
                for i in range(len(apps)):
                    #print '------------',apps[i].find_element(By.ID,r'com.tclmarket:id/name').text
                    try:
                        if apps[i].find_element(By.ID,r'com.tclmarket:id/name').text == name:
                            apps[i].find_element(By.ID,r'com.tclmarket:id/actionOne').click()
                            self.common_fn.element_clk('OK',By.NAME)
                            return True
                    except:
                        s = sys.exc_info()
                        print 'Error "%s" happend on line %d' % (s[1],s[2].tb_lineno)
                newLastAPP = apps[-1].find_element(By.ID,r'com.tclmarket:id/name').text
                if lastAPP == newLastAPP:
                    return False
                lastAPP = newLastAPP
                self.common_fn.swipe_screen(percent=0.7,duration=2000)
        except:
            s = sys.exc_info()
            print 'Error "%s" happend on line %d' % (s[1],s[2].tb_lineno)
class startOperate():
    """4.0.1启动类"""

    #----------------------------------------------------------------------
    def __init__(self):
        """Constructor"""
        self.common_fn = CommonFunctions()
        
    #----------------------------------------------------------------------
    def baseOperate(self):
        """4.0.1版本基本操作"""
        
        #关闭升级提示
        if not self.common_fn.wait_for_element(r'android:id/alertTitle',By.ID) == None:
            print 'find alertTitle'
            self.common_fn.element_clk(r'android:id/button2')
            
        time.sleep(5)
        
        return True
class startSearchPage():
    def __init__(self):
        self.common_fn = CommonFunctions()

    def appHomePage(self):
        try:
    
            downloadApps=self.common_fn.wait_for_elements(r'com.tclmarket:id/item_container',By.ID)
            isClick = False
            for app in downloadApps:
                downloadBtn = app.find_element(By.ID,r'com.tclmarket:id/action_text')
                if downloadBtn.text == u'下载':
                    downloadBtn.click()
                    isClick = True
                    break
            if not isClick:
                raise Exception('do not have download app at installedAppOpen')
            print u'start to download an app\n'
            time.sleep(50)
        except:
            print u'fail to download the first app\n ' 
        try:
            for i in range(4):
                self.common_fn.element_clk(r'com.android.packageinstaller:id/ok_button',timeout=50)
                print u'click the next button %d\n' % (i+1)
            time.sleep(30)
            print u'finish clicking ok\n'
        except:
            print u'something wrong with ok button\n'
        try:
            doneButton=self.common_fn.element_clk(r"com.android.packageinstaller:id/done_button",timeout=30)
            time.sleep(2)
            print u'install the first app\n'         
        except:
            print u'fail to install the first app\n'           
        try:
            manageButtons=self.common_fn.wait_for_elements(r'com.tclmarket:id/text',By.ID)
            if manageButtons[4].text==u'管理':
                manageButtons[4].click()
                time.sleep(2)
                print u'go into manage page\n'
            else:
                print u'manageButton[4].text do not equal to 管理'    
        except:
            print u'not find manage button\n'
            s = sys.exc_info()
            print 'Error %s happend on line %d' % (s[1],s[2].tb_lineno)
              
            
    def appDownloadTask(self):
        try:
            
            downloadTaskButtons=self.common_fn.wait_for_elements(r'com.tclmarket:id/manage_image',By.ID)
            downloadTaskButtons[0].click()
            time.sleep(2)
            
            print u'go into download task page'
        except:
            print u'fail to go into download task page'
                        
    def startSearchPage(self):
        try:
            self.appHomePage()
            self.appDownloadTask()
            appName = self.common_fn.wait_for_element(r'com.tclmarket:id/name').text
            searchButton=self.common_fn.wait_for_element(r'com.tclmarket:id/actionbar_search')
            searchButton.click()
            time.sleep(2)
            try:
                findAppButton=self.common_fn.wait_for_element(r'com.tclmarket:id/search_editor')
                if findAppButton.text==u'搜您喜欢的应用':
                    print u'get search page\n'
                    try:
                        gobackButton=self.common_fn.wait_for_element(r'com.tclmarket:id/actionbar_up')
                        gobackButton.click()
                        time.sleep(2)
                        try:
                            title=self.common_fn.wait_for_element(r'com.tclmarket:id/home_title')
                            if title:
                                print u'goback to download task page\n'
                                base = baseFunc()
                                base.uninstallAPP(appName)                                
                                return True
                            else:
                                print u'fail to goback to download task page\n'    
                                return False
                        except:
                            s = sys.exc_info()
                            print 'Error %s happend on line %d' % (s[1],s[2].tb_lineno)
                            return False        
                    except:
                        print u'not find gobackButton\n'    
                        return False
                else:
                    print u'fail to get search page\n'
                    return False
            except:
                print u'not get the findAppButton'        
                return False
        except:
            print u'fail to find search button\n'
            return False
        finally:
            self.common_fn.driver.remove_app('com.tencent.qqlive')        
            
    def run(self):
        start = startOperate()
        return self.common_fn.run_test_case(lambda: self.common_fn.launch_app('4.0.1'),
                                     lambda: start.baseOperate(),
                                     lambda: self.startSearchPage()) 
class apk_scanning_page():
    '''
                      版本 应用商店4.0.1
                     编号  AppStore2-935 
                    标题    安装包扫描界面
      '''
    def __init__(self):
        self.common_fn = CommonFunctions()
    
                                    
    def app_homepage(self):
        try:
            downloadApps=self.common_fn.wait_for_elements(r'com.tclmarket:id/item_container',By.ID)
            isClick = False
            for app in downloadApps:
                downloadBtn = app.find_element(By.ID,r'com.tclmarket:id/action_text')
                if downloadBtn.text == u'下载':
                    downloadBtn.click()
                    appName = app.find_element(By.ID,r'com.tclmarket:id/name').text
                    isClick = True
                    break
            if not isClick:
                raise Exception('do not have download app at installedAppOpen')
            print u'start to download an app\n'
            time.sleep(50)
        except:
            print u'fail to download the first app\n ' 
        try:
            for i in range(4):
                self.common_fn.element_clk(r'com.android.packageinstaller:id/ok_button')
                #print u'click the next button %d\n' % (i+1)
            time.sleep(30)
            #print u'finish clicking ok\n'
        except Exception as e:
            print e
            print u'something wrong with ok button\n'
            return False 
        try:
            self.common_fn.element_clk(r"com.android.packageinstaller:id/done_button")
            time.sleep(2)
            #print u'install the first app\n'         
        except:
            print u'fail to install the first app\n'     
            return False
        try:
            download_apps=self.common_fn.wait_for_elements(r'com.tclmarket:id/action',By.ID)
            download_apps[1].click()
            print u'start to download the second app\n'
            time.sleep(55)
        except:
            print u'fail to download the second app\n ' 
            return False
        try:    
            self.common_fn.wait_for_element(r'com.android.packageinstaller:id/cancel_button',time_out=90).click() 
            time.sleep(2)
            print u'refuse to install downloaded apk\n'
        except:
            print u'fail to refuse install\n'     
            return False
        finally:
            self.common_fn.driver.remove_app('com.tencent.qqlive') 
            
        try:
            manage_buttons=self.common_fn.wait_for_elements(r'com.tclmarket:id/text',By.ID)
            if manage_buttons[4].text==u'管理':
                manage_buttons[4].click()
                time.sleep(2)
                print u'go into manage page\n'
            else:
                print u'manageButton[4].text do not equal to 管理'
                return False
            try:
                action_buttons=self.common_fn.wait_for_elements(r'com.tclmarket:id/manage_image',By.ID)
                action_texts=self.common_fn.wait_for_elements(r'com.tclmarket:id/manage_text',By.ID)
                if action_texts[3].text==u'安装包扫描' :
                    action_buttons[3].click()
                    print u'get apks scanning page\n'
                else:
                    print u'not get apks scanning page\n'
                    return False 
                try:
                    title=self.common_fn.wait_for_elements(r'com.tclmarket:id/header_text',By.ID)
                    base = baseFunc()
                    if title and len(title) == 1 and u'已安装' in title[0].text:
                        base.uninstallAPP(appName)
                        return True
                    elif title and len(title) == 2 and u'已安装' in title[0].text and u'未安装' in title[1].text:
                        #print u'installed apk is right\n'
                        base.uninstallAPP(appName)
                        return True
                    else:
                        print u'没有发现已安装或未安装列表'
                        return False 
                except:
                    print u'not find apks\n'  
                    s = sys.exc_info()
                    print 'Error "%s" happend on line %d' % (s[1],s[2].tb_lineno)                   
                    return False 
            except:
                print u'not find apks scanning button\n'
                s = sys.exc_info()
                print 'Error "%s" happend on line %d' % (s[1],s[2].tb_lineno)
                return False
        except:
            print u'not find manage button\n'
            s = sys.exc_info()
            print 'Error "%s" happend on line %d' % (s[1],s[2].tb_lineno)            
            return False
        
       
    def run(self):
        start = startOperate()
        return self.common_fn.run_test_case(lambda: self.common_fn.launch_app('4.0.1'),
                                     lambda: start.baseOperate(),
                                     lambda: self.app_homepage())