import requests
from lxml import html
import copy

from PythonPlugin import PythonPlugin

import os
import logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
    datefmt='%Y-%m-%d %H:%M:%S',
    filename=os.path.join(os.path.abspath(
        os.path.dirname(__file__)), 'CQHanlder.log'),
    filemode='w+'
)

result_template = {
    'Title': '{}',
    'SubTitle': 'Press enter copy magnet url',
    'IconPath': 'img/app.png',
    'Action': {
        'FuncName': 'Ra_CopyPath',
        'Parameter': '{}',
    }
}

class Main(PythonPlugin):

    def Query(self, param):
        results = []
        q = param.strip()
        if not q:
            results.append({
            "Title": "磁链搜索",
            "SubTitle": "Search on BTSHOW",
            "IconPath":"img/app.png"
            })
            return results
        
        searchTUrl = "https://btsow.space/search/@key"
        searchUrl = searchTUrl.replace('@key', q)
        logging.info(searchUrl)

        response = self.search(searchUrl)
        if not response:
            results.append({
            "Title": "磁链搜索",
            "SubTitle": "have no results",
            "IconPath":"img/app.png"
            })
            return results

        logging.info(response)    
        return response
        
    @staticmethod
    def search(searchUrl):
        s = requests.session()
        headers = {
            'user-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.79 Safari/537.36',
            'accept-language': 'en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7'}

        res = s.get(searchUrl, headers=headers)
        if res.ok:
            results = []

            tree = html.fromstring(res.content.decode('utf-8'))
            resultList = tree.cssselect(".data-list .row")
            if len(resultList) == 0:
                return None

            for item in resultList:
                result = copy.deepcopy(result_template)
                a_label_list = item.cssselect("a")
                if not a_label_list:
                    continue
                a_label = a_label_list[0]
                videoName = a_label.get('title')
                result['Title'] = result['Title'].format('{}'.format(videoName))
                logging.info(videoName)

                magnetUrl = a_label.get('href')
                magnetUrl = magnetUrl[magnetUrl.rindex('/')+1:]
                magnetUrl = 'magnet:?xt=urn:btih:' + magnetUrl
                result['Action']['Parameter'] = result['Action']['Parameter'].format(magnetUrl)
                
                results.append(result)
                result = None
            return results
        else:
            logging.info('connect url failed')
            return None

if __name__ == '__main__':
    #print(Main().Query("IPA"))
    Main()
