import requests
from lxml import html
import clipboard
import copy
import re

from PythonPlugin import PythonPlugin

class Main(PythonPlugin):

    def Query(self, param):
        results = []
        q = param.strip()
        if not q:
            results.append({
            "Title": "新浪短链",
            "SubTitle": "Get short url",
            "IconPath":"img/app.png"
            })
            return results
           
        if q[0:4] != "http":
            q = "http://" + q
        
        if not re.match(r"^(http://){0,1}[A-Za-z0-9][A-Za-z0-9\-\.]+[A-Za-z0-9]\.[A-Za-z]{2,}[\43-\176]*$",q):
            results.append({
            "Title": "新浪短链",
            "SubTitle": "LongUrl: %s" % q,
            "IconPath":"img/app.png"
            })
            return results
            
        response = self.getshorturl(q)
        if not response:
            results.append({
            "Title": "新浪短链",
            "SubTitle": "Get short url failed",
            "IconPath":"img/app.png"
            })
            return results
        
        results.append({
                "Title": "新浪短链",
                "SubTitle": "ShortUrl: %s" % response,
                "IconPath":"img/app.png",
                "Action": {
                    'FuncName': 'Ra_CopyPath',
                    'Parameter': response
                }
            })
            
        return results
            
            
    def copytoclipboard(self, value):
        clipboard.copy(value)

    @staticmethod
    def getshorturl(url):
        api_url = "http://api.t.sina.com.cn/short_url/shorten.json?source=3271760578&url_long=" + url
        s = requests.session()
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko'}
        res = s.get(api_url, headers=headers)
        if res.ok:
            resultData = res.content.decode('utf-8')
            dictData = eval(resultData)
            short_url = dictData[0]['url_short']
            return short_url
        else:
            return ""

if __name__ == '__main__':
    Main()
