'''
1、启动appium服务
    subproccess
    配置文件
1.1、校验服务是否启动
1.2、杀掉上一次的服务
2、启动driver

'''

from lib.tools import Tool
import subprocess
from lib.path import SYSTEMPATH, ERRORPATH
import time
from appium import webdriver
import queue
# 声明一个python队列
driver_queue = queue.Queue()




class Controller(object):
    def __init__(self):
        # 获取配置信息
        self.config = Tool().get_config

        self.tester = self.config.get('tester')
        self.device_type = self.config.get('device_type')
        # 获取到所有的手机信息
        self.devices = self.config.get('devices')
        self.device = self.devices.get(self.device_type)[0]
        # port 用于校验服务是否启动
        self.port = self.device.get('port')
        self.name = self.device.get('name')

    def kill_server(self):
        mac = '''ps -ef|grep appium|grep -v grep|grep %s|awk '{print "kill -9 " $2}'|sh''' % self.port
        win = 'taskkill /F /IM node.exe /t'
        subprocess.getoutput(win)

    def start_server(self):
        self.kill_server()
        command = 'appium -a {ip} -p {port} -U {deviceName}'.format(ip=self.device.get('ip'),
                                                                    port=self.device.get('port'),
                                                                    deviceName=self.device.get('deviceName'))
        print('command : %s' % command)
        subprocess.Popen(command, stdout=open(SYSTEMPATH, 'a+'), stderr=open(ERRORPATH, 'a+'), shell=True)

    def test_server(self):
        # mac = 'ps -ef|grep appium|grep -v grep|grep %s' % self.port
        win = 'netstat -ano | findstr %s' % self.port
        time.sleep(3)
        while True:
            data = subprocess.getoutput(win)
            if data:
                time.sleep(10)
                print('%s 端口启动成功。' % self.port)
                break
            else:
                print('%s 端口启动失败。5秒后重试。' % self.port)
                time.sleep(5)
        return True

    def start_driver(self):

        url = 'http://{ip}:{port}/wd/hub'.format(ip=self.device.get('ip'),
                                                 port=self.port)
        # 合并手机信息和包名入口
        self.device.update(self.tester)
        driver = webdriver.Remote(url, self.device)
        driver_queue.put(driver)


if __name__ == '__main__':
    controller = Controller()
    controller.start_server()
    if controller.test_server():
        controller.start_driver()
[(18, 'queue.Queue', 'queue.Queue', False, 'import queue\n'), (40, 'subprocess.getoutput', 'subprocess.getoutput', False, 'import subprocess\n'), (53, 'time.sleep', 'time.sleep', False, 'import time\n'), (71, 'appium.webdriver.Remote', 'webdriver.Remote', False, 'from appium import webdriver\n'), (26, 'lib.tools.Tool', 'Tool', False, 'from lib.tools import Tool\n'), (55, 'subprocess.getoutput', 'subprocess.getoutput', False, 'import subprocess\n'), (57, 'time.sleep', 'time.sleep', False, 'import time\n'), (62, 'time.sleep', 'time.sleep', False, 'import time\n')]