import time
from ctypes import *
from tcping import Ping


def ping_ip(ip_address, request_nums):
    """
    ping ip
    :param ip_address:
    :param request_nums: 请求次数
    :return: 丢包率loss和统计结果res
    """
    ping = Ping(ip_address, 2077, 3)
    ping.ping(request_nums)
    res = ping.result.table
    ret = ping.result.raw
    return_list = list(ret.split('\n'))
    loss = return_list[2].split(',')[3].split(' ')[1]  # 获取丢包率
    return loss, res


def ping_process(host):
    # 调用ping_ip方法得到丢包率
    loss, res = ping_ip(host, 3)
    if float(loss.strip('%')) / 100 <= 0.1:  # 0.1为自定义丢包率阈值，可修改
        print("ping 不通")
    else:
        print("ping 通")


def shut_screen_and_lock():
    windll.user32.PostMessageW(0xffff, 0x0112, 0xF170, 2)
    shell32 = windll.LoadLibrary("shell32.dll")
    shell32.ShellExecuteW(None, 'open', 'rundll32.exe', 'USER32,LockWorkStation', '', 5)


def is_locked():
    # 导入 user32.dll
    user32 = windll.User32

    # 检查锁定状态, 如果结果为0，则系统处于锁定状态，否则系统处于解锁状态
    result = user32.GetForegroundWindow()
    return True if result == 0 else False


class AutoSafe:
    """

    """

    def __init__(self, cool_down_time: int, delay_time: int, target_server: str):
        self.cool_down_time = cool_down_time
        self.delay_time = delay_time
        self.target_server = target_server
        self.start_monitor = True

    def check_connection(self) -> bool:
        loss, res = ping_ip(self.target_server, 5)
        if float(loss.strip('%')) / 100 <= 0.1:
            return False
        else:
            return True

    def run(self):
        print("Starting AutoSafe")
        while self.start_monitor:
            time.sleep(20)
            if is_locked() or self.check_connection():
                continue
            else:
                self.safe()

    def safe(self):
        print('Safe armed at ' + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
        time.sleep(self.delay_time)
        if not is_locked() and not self.check_connection():
            print('Safe activated at ' + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
            shut_screen_and_lock()
            time.sleep(self.cool_down_time)
        return


if __name__ == '__main__':
    auto_safe = AutoSafe(cool_down_time=3600 * 8, delay_time=60, target_server='192.168.195.194')
    auto_safe.run()
    # ping('192.168.195.194')
    # while 1:
    #     print(is_locked(), time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
    #     time.sleep(1)
