# coding: utf-8
import os, sys, json,time 
from base import *
from files_tools import *
import winreg

# 获取pip安装模块列表
def get_pip_list():
    rRet = ExecShell(get_run_pip('[PIP] list'))
    list = rRet[0].split('\r\n')
    import re
    data = {}
    i = 0
    for x in list:
        if i > 1:
            temp = re.search('([\w-]+)\s+([\d\.]+)', x)
            if temp:
                key = temp.groups()[0]
                version = temp.groups()[1]

                item = {}
                item['version'] = version
                data[key] = item
        i += 1
    return data

#获取运行python脚本
def get_run_python(shell):
    shell = shell.replace('[PYTHON]', '"C:/Program Files/python/python.exe"')
    shell = to_path(shell)
    return shell

# 获取运行pip脚本
def get_run_pip(shell):
    shell = shell.replace('[PIP]', '"C:\Program Files\python\python.exe" -m pip')
    return shell

def kill(name, username=None):
    """
    结束指定进程
    @name 进程名
    @username 按进程和运行用户结束
    """
    shell = "taskkill /f /t /im %s" % name
    if username:
        shell = 'taskkill /f /t /fi "username eq %s" /im %s ' % (username, name)
    os.system(shell)

def ReadReg(path, key):
    """
    读取注册表
    @path 注册表路径
    @key 注册表键值
    """
    import winreg
    try:
        newKey = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path)
        value, type = winreg.QueryValueEx(newKey, key)
        return value
    except:
        return False

def DelReg(path, key):
    """
    删除注册表
    @path 注册表路径
    @key 注册表键值
    """
    import winreg
    try:
        newKey = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path)
        winreg.DeleteKey(newKey, key)
        return True
    except:
        return False


def WriteReg(path, key, value, type=winreg.REG_SZ):
    """
    写入/创建注册表
    @path 注册表路径
    @key 注册表键值
    @value 注册表值
    @type 注册表值类型
    """
    import winreg
    try:
        newKey = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path, 0, winreg.KEY_ALL_ACCESS)
    except:
        newKey = winreg.CreateKey(winreg.HKEY_LOCAL_MACHINE, path)
    try:
        # SetValue 只支持字符串，其他类型使用SetValueEx
        if isinstance(value, int):
            winreg.SetValueEx(newKey, key, 0, winreg.REG_DWORD, value)
        else:
            winreg.SetValueEx(newKey, key, 0, type, value)
        return True
    except Exception as ex:

        return False

#win作废函数
def get_mode_and_user():
    pass

#win作废函数
def set_mode():
    pass

#win作废函数
def set_own(filename, user, group=None):
    pass
    
#win作废函数
def set_ownership(directory, user):
    pass