# coding:utf-8
# -*- coding: utf-8 -*-
#import urllib.request
import requests
import hashlib
#import sys
#reload(sys)
#sys.setdefaultencoding('utf-8')
from time import sleep


user_headers={
'accept': 'application/json, text/javascript, */*; q=0.01',
'accept-encoding': 'gzip, deflate, br',
'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
'origin': 'http://www.weather.com.cn',
'referer': 'http://www.weather.com.cn/',
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36 Edg/87.0.664.57'
}

def get_weather(localcode): 
    
    url="http://www.weather.com.cn/weather/"+str(localcode)+".shtml"
    req=requests.get(url,headers=user_headers)
    #f_str=urllib.request.urlopen(req).read().decode('utf-8')
    req.encoding="utf-8"
    f_str=req.text
    f1=str(f_str)
    #print(f1)
    f_on=f1.find("fc_24h_internal_update_time")
    f_off=f1.find("（明天）")
    f_today=f1[f_on:f_off]
    w1=f_today.find("wea")+5 #start position of today's weather
    w2=f_today.find("tem")-15 #end positon of today's weather
    f_tdw=f_today[w1:w2]
    res=[]
    res.append(f_tdw)
    t1=f_today.find("tem")+7 #start position of today's temperature
    t2=f_today.find("win")-20 #end positon of today's temperature
    f_tdt=f_today[t1:t2]
    ctrl_1=f_tdt.find("</span>/<i>")
    if ctrl_1==-1:
        ctrl_1=f_tdt.find("i>")+2
        ctrl_2=f_tdt.find("℃")
        temp=f_tdt[ctrl_1:ctrl_2]+ " C "
    else:
        ctrl_2=ctrl_1+11
        tem_h=f_tdt[5:ctrl_1] #high temperature
        tem_l=f_tdt[ctrl_2:-1] #low tempterature
        temp=tem_l+"/"+tem_h +" C "
    res.append(temp)
    win1=f_today.find("win")
    win2=f_today.find("/em")+20
    wind0=f_today[win1:win2]
    win3=wind0.find("class")+7
    win4=wind0.find("/span")-3
    windn=wind0[win3:win4] #the direction of wind is "windn"
    res.append(windn)
    #print(windn)
    win5=wind0.find("<i>")+3
    win6=wind0.find("</i>")
    windg=wind0[win5:win6-1].replace("级","").replace("转"," to ") #the grade of wind is "windg"
    res.append(windg)
    #print("windg=",windg)
    return res
    

def md5sum(s):
    return hashlib.md5(s.encode("utf-8")).hexdigest()

def translate(word):
    q=word
    from1="zh"
    to="en"
    appid="20201212000645063"
    scode="HEhjErB3C9EQzQdtZklq"
    salt=1435660288
    sign=md5sum(appid+q+str(salt)+scode)
    url="http://api.fanyi.baidu.com/api/trans/vip/translate"
    rep=url+"?q="+q+"&from="+from1+"&to="+to+"&appid="+appid+"&salt="+str(salt)+"&sign="+sign
    try:
        req=requests.get(rep)
        req.encoding="utf-8"
        tmp=req.text
        while(tmp.find('code":"54003')!=-1):
            #print(tmp)
            sleep(1.1)
            req=requests.get(rep)
            req.encoding="utf-8"
            tmp=req.text
        res=tmp[tmp.find("dst")+6:-4]
    except:
        res="Translate Trror!"
    return res

    
# this function doesn't work, because I didn't find any website that put aqi index on the html document. some use complex items, and some use ajax which python cannot deal with it
def get_aqi():
    #url="https://www.mee.gov.cn"
    url="http://106.37.208.228:8082/"
    req=requests.get(url,headers=user_headers)
    #f_str=urllib.request.urlopen(req).read().decode('utf-8')
    req.encoding="utf-8"
    f_str=req.text
    f1=str(f_str)
    print(f1)
# please don't use this function until I fixed those problems!




if __name__=="__main__":    
    print("+-----------------------------------+")
    print("|          Weather Get V2.0         |")
    print("|   modified by zwy at Dec12,2020   |")
    print("+-----------------------------------+")
    print("Get today's weather from http://www.weather.com.cn\n")
    
    weathermartrix=[
    ["哈尔滨",  101050101,""],
    ["呼和浩特",101080101,""],
    ["乌鲁木齐",101130101,""],
    ["北京",    101010100,""],
    ["天津",    101030100,""],
    ["石家庄",  101090101,""],
    ["兰州",    101160101,""],
    ["郑州",    101180101,""],
    ["淮南",    101220401,""],
    ["信阳",    101180601,""],
    ["上海",    101020100,""],
    ["温州",    101210701,""],
    ["武汉",    101200101,""],
    ["长沙",    101250101,""],
    ["重庆",    101040100,""],
    ["福州",    101230101,""],
    ["广州",    101280101,""],
    ["海口",    101310101,""],
    ]
    
    print("{:_^78}".format(""))
    tplt="{0:{5}^7}|{1:{5}^8}|{2:^12}|{3:^16}|{4:^12}"
    print(tplt.format("地区","天气","Wind","WindGrade","Temp",chr(12288)))
    print("{:-^78}".format(""))
    for i in range(0,len(weathermartrix)):
        weathermartrix[i][2]=get_weather(weathermartrix[i][1])
        print(tplt.format(weathermartrix[i][0],weathermartrix[i][2][0],weathermartrix[i][2][2],weathermartrix[i][2][3],weathermartrix[i][2][1],chr(12288)))
    print("{:=^78}".format(""),end="\n\n")
    
    #TODO:
    #翻译模块已写好，传入中文字符串，返回英文字符串。
    #天气爬取模块使用的依然是旧版网页，可能存在失效的风险。
    #目前能获取的数据包括当前天气、温度、风力与风向。
    #！！！希望增加获取空气污染指数的代码。
    #！！！如果能够升级接口将更好。
    #main函数的输出代码也要升级，把那两个内容加进去。
    #2020-12-12 02:15 by zwy

    #UPDATE:
    #修改了WindGrade的显示内容，不会因为中文字符与英文字符同时出现导致乱码。
    #添加了几个城市
    #暂时没有升级接口的打算
    #2021-03-28 15:45 by zwy

    #UPDATE:
    #发现了另一个有官方背景的天气数据网站
    # https://weather.cma.cn/web/weather/54511
    #近期如果有空，可以尝试升级一下接口。
    #2021-9-9 19:06 by zwy


