import json
import os
import shutil
import stat
from loguru import logger

import requests


class VmLogin:
    def __init__(self, token):
        self.token = token

    def get_remotely_url(self, path):
        """
        vmlogin 远程地址
        :param path:
        :return:
        """
        return f"https://api.vmlogin.com/v1{path}"

    def get_chrome_config(self, profile_id, start_url='', proxy=None):
        """
        获取修改后的浏览器配置
        :param profile_id:  配置ID
        :param start_url:   打开地址
        :return:ilo29@
        """
        url = self.get_remotely_url(f'/profile/detail?token={self.token}&profileId={profile_id}')
        json_text = self.request_get(url)
        print(json.dumps(json_text))
        json_text['proxyServer']['setProxyServer'] = True
        json_text['startUrl'] = start_url
        json_text['proxyServer']['port'] = proxy['port']
        json_text['proxyServer']['host'] = proxy['host']
        json_text['proxyServer']['username'] = proxy.get('username', '')
        json_text['proxyServer']['password'] = proxy.get('password', '')
        return json_text

    def create_chrome_config(self, body, user_agent, name="关键词上首页"):
        """
        创建浏览器配置
        :param body:
        :param user_agent:
        :return:
        """
        body['name'] = name
        body['userAgent'] = user_agent
        body['localCache']['deleteCache'] = True
        body['localCache']['deleteCookie'] = True
        body['localCache']['clearCache'] = True
        body['localCache']['clearHistory'] = True
        headers = {'Content-Type': 'application/json'}
        url = self.get_remotely_url('/profile/create')
        text = requests.post(url, headers=headers,
                             data=json.dumps({"token": self.token, "Body": body})).json()
        return text['value']

    def get_local_url(self, path):
        """
        vmlogin 本地地址
        :param path:
        :return:
        """
        return f"http://127.0.0.1:35000/api/v1{path}"

    def start_chrome(self, profile_id):
        """
        启动浏览器
        :param profile_id:  配置ID
        :return:
        """
        url = self.get_local_url(f'/profile/start?profileId={profile_id}')
        text = requests.get(url).json()
        if text['status'] == 'ERROR':
            return ''
        return ('' + text['value']).replace("http://127.0.0.1:", "")

    def request_get(self, url, params=None):
        """
        发送请求
        :param url: 请求地址
        :param params: 请求参数
        :return: 配置信息
        """
        headers = {
            'User-Agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36 Edg/96.0.1054.62"
        }
        return requests.get(url, headers=headers, params=params).json()

    def get_rand_ua(self):
        """
        获取随机请求头
        :return:
        """
        url = self.get_local_url(f'/profile/randomProfile?token={self.token}&platform=Windows&browser=chrome')
        json_text = self.request_get(url)
        return json_text['userAgent']

    def stop_chrome(self, profile_id):
        """
        停止浏览器
        :param profile_id:
        :return:
        """
        url = self.get_local_url(f'/profile/stop?profileId={profile_id}')
        self.request_get(url)

    def delete_config(self, profile_id, path="C:\\Users\\Administrator\\AppData\\Roaming\\VMLogin\\profile"):
        """
        删除配置文件
        :param profile_id: 配置ID
        :return:
        """
        url = self.get_remotely_url(f'/profile/remove?token={self.token}&profileId={profile_id}')
        requests.get(url)
        self.delete_file(path)

    def delete_file(self, file_path):
        """
        删除文件
        :param file_path:  文件地址
        :return:
        """
        if os.path.exists(file_path):
            for fileList in os.walk(file_path):
                for name in fileList[2]:
                    os.chmod(os.path.join(fileList[0], name), stat.S_IWRITE)
                    os.remove(os.path.join(fileList[0], name))
            shutil.rmtree(file_path)
            return "delete ok"
        else:
            return "no filepath"

    def import_cookie(self, profile_id: str, cookie: dict) -> dict:
        """
        导入cookie

        :param profile_id:
        :param cookie:
        :return:
        """
        url = self.get_local_url('/profile/cookies/import/webext')
        data = {
            'profileId': profile_id,
            'body': cookie,
        }
        return requests.post(url=url, data=data).json()


if __name__ == '__main__':
    token = '6731ae7034426c1f861479eaeb964c61'
    data = VmLogin(token).get_chrome_config('0B3D6BAF-E534-4CE5-A53B-75D405378E39')
    print(data)
