#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
#CPU compare
#GPU compare
#比较不同cpu或gpu的性能差异
import readline
import requests
import json
import os
import sys

cpu_value = [] #cpu和gpu使用同一个变量
cpu_data = [] #'value': 'Intel Core i5-12600KF', 'data': '4625'
compare_value = []
compare_data = []
mode = 0 #0:cpu 1:gpu
cookie = []

Hostreferer = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36'
}

def show_list():
    global compare_data,compare_value
    i = 0
    while i < len(cpu_value):
        print("\t【"+str(i+1)+"】"+cpu_value[i])
        i += 1
    sid = input("(多项用空格隔开)请选择:")
    if str(sid).strip() == "":
        return
    elif str(sid).strip() == "0":
        select_cpu_or_gpu()
        return
    nl_ = str(sid).strip().split(" ")
    nl = []
    for k in nl_:
        if k:
            nl.append(k)
    
    if len(nl) > 1:
        j = 0
        while j < len(nl):
            if nl[j] != "":
                compare_value.append(cpu_value[int(nl[j])-1])
                compare_data.append(cpu_data[int(nl[j])-1])
                j += 1
    else:
        if nl[0] != "":
            compare_value.append(cpu_value[int(nl[0])-1])
            compare_data.append(cpu_data[int(nl[0])-1])
        


def uniq_compare_list():
    global compare_data,compare_value
    l2 = list(set(compare_data))
    l2.sort(key=compare_data.index)
    compare_data = l2
    l2 = list(set(compare_value))
    l2.sort(key=compare_value.index)
    compare_value = l2
    return
    
    
    
    
def save_to_html(result):
    htmlfile = "/tmp/result.html"
    file_obj = open(str(htmlfile),'w',encoding='UTF-8', newline='')
    file_obj.write(result)
    file_obj.close()
    cmdline = ('sh -c \'surf -t -a a -d -g -b -n -m -X %s 2>/dev/null &\''%(htmlfile))
    os.system(cmdline)
    

def show_compare_result():
    link = ""
    link2 = ""
    link3 = ""
    if len(compare_data) < 6 and len(compare_data) > 1:
        i = 0
        while i < len(compare_data):
            link += str(compare_value[i]).split("@")[0].strip().replace(" ","-")+'-vs-'
            link2 += str(compare_data[i])+'vs'
            i += 1
        if mode == 0:
            link3 = "https://www.cpubenchmark.net/compare/"+str(link).rstrip("-vs-")+"/"+str(link2).rstrip('vs')
        else:
            link3 = "https://www.videocardbenchmark.net/compare/"+str(link).rstrip("-vs-")+"/"+str(link2).rstrip('vs')
        res = requests.get(link3,headers=Hostreferer)
        result = ("<table id=\"detailsbox\""+res.text.split("<table id=\"detailsbox\"")[1].split("</table>")[0]+"</table>")
        save_to_html(result)
        return
    else:
        i = 0
        while i < 5:
            link += str(compare_value[i]).split("@")[0].strip().replace(" ","-")+'-vs-'
            link2 += str(compare_data[i])+'vs'
            i += 1
        if mode == 0:
            link3 = "https://www.cpubenchmark.net/compare/"+str(link).rstrip("-vs-")+"/"+str(link2).rstrip('vs')
        else:
            link3 = "https://www.videocardbenchmark.net/compare/"+str(link).rstrip("-vs-")+"/"+str(link2).rstrip('vs')
        res = requests.get(link3,headers=Hostreferer)
        result = ("<table id=\"detailsbox\""+res.text.split("<table id=\"detailsbox\"")[1].split("</table>")[0]+"</table>")
        save_to_html(result)
        print("\t\t【最多5个数据比较】")
        return        
        
            
            
        
        

    


def search():
    global cpu_data,cpu_value,compare_data,compare_value
    while True:
        cpu_value = []
        cpu_data = []
        key = ""
        if len(compare_value) > 0:
            uniq_compare_list()
            if mode == 0:
                print("已添加的CPU")
            else:
                print("已添加的GPU")
            for j in compare_value:
                print(j)
        else:
            print("当前比较列表为空")
        
        if mode == 0:
            key = input("(0:首页,clear:清空候选列表,exit():退出)添加CPU:")
        else:
            key = input("(0:首页,clear:清空候选列表,exit():退出)添加GPU:")
        if str(key) == "exit()":
            os.system('clear')
            sys.exit()
        elif str(key) == "" and len(compare_data) > 1:
            show_compare_result()
            compare_value = []
            compare_data = []
            continue
        elif str(key) == "" and len(compare_data) < 2:
            print("\t\t【至少2个数据】")
            continue
        elif str(key) == "clear":
            compare_value = []
            compare_data = []
            os.system('clear')
            continue
        elif str(key).strip() == "":
            continue
        elif str(key).strip() == "0":
            select_cpu_or_gpu()       
            continue
        url = ""
        hdr = {}
        if mode == 0:
            url = "https://www.cpubenchmark.net/autocomplete/cpu/?query="+str(key).strip()
            hdr = {
                "cookie": cookie[0],
                "referer": "https://www.cpubenchmark.net/singleCompare.php",
                "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36",
                "x-requested-with": "XMLHttpRequest"
            
            }            
        else:
            url = "https://www.videocardbenchmark.net/autocomplete/gpu/?query="+str(key).strip()
            hdr = {
                "cookie": cookie[1],
                "referer": "https://www.videocardbenchmark.net/singleCompare.php",
                "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36",
                "x-requested-with": "XMLHttpRequest"
            }            
            
        res = requests.get(url,headers=hdr).json()
        if res['suggestions'] == []:
            os.system('clear')
            continue
        i = 0
        while i < len(res['suggestions']):
            value = (res['suggestions'][i]['value'])
            data = (res['suggestions'][i]['data'])
            cpu_value.append(value)
            cpu_data.append(data)
            i += 1
        show_list()


def get_cookie():
    try:
        global cookie
        print("正在获取cookie")
        url = ["https://www.cpubenchmark.net/singleCompare.php","https://www.videocardbenchmark.net/singleCompare.php"]
        Hostreferer = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36'
        }
        i = 0
        while i < len(url):
            html = requests.get(url[i], headers=Hostreferer)
            if html.status_code == 200:
                for ck in html.cookies:
                    cookie.append(str(ck).split(" ")[1])
            i += 1
        print("Cookie获取成功!")
    except:
        print("Cookie获取失败!")


def select_cpu_or_gpu():
    global mode,cookie,compare_data,compare_value,cpu_data,cpu_value
    compare_data = []
    compare_value =[]
    cpu_data = []
    cpu_value = []
    os.system('clear')
    print("选择查询的内容")
    print("1:CPU")
    print("2:GPU")
    sid = ""
    sid = input("选择:")
    if str(sid).strip() == "1":
        mode = 0
        os.system('clear')
        return
    elif str(sid).strip() == "2":
        mode = 1
        os.system('clear')
        return        
    else:
        return select_cpu_or_gpu()
    
    

    


if __name__ == '__main__':
    os.system('clear')
    get_cookie()
    select_cpu_or_gpu()
    search()