#coding=utf-8

import requests
import datetime
import pandas as pd
import numpy as np
from bs4 import BeautifulSoup

# get_metadata(obj): pass a bs4 obj, return a list which contains some meta data of one day's weather
"""
example:
pass an object like this:
<div class="pull-left day actived">
<div class="day-item">星期一<br/>10/04</div>
<div class="day-item dayicon"><img src="/static/img/w/icon/w7.png"/></div>
<div class="day-item">小雨</div>
<div class="day-item">北风</div>
<div class="day-item">微风</div>
<div class="day-item bardiv"><div class="bar" style="top:1px; bottom:0px;"><div class="high">18℃</div><div class="low">12℃</div></div></div>
<div class="day-item nighticon"><img src="/static/img/w/icon/w7.png"/></div>
<div class="day-item">小雨</div>
<div class="day-item">无持续风向</div>
<div class="day-item">微风</div>
</div>

and return a list like this:
['10/04','小雨','北风','微风','18','12','小雨','无持续风向','微风']
"""
def get_metadata(obj): # pass a bs4 obj, return a list which contains some meta data of one day's weather
    ls = []
    for i in obj.contents:
        if(i!="\n"):ls.append(i.contents[-1])
    ls[5] = ls[5].contents[1].contents[0].replace("℃","/")+ls[5].contents[0].contents[0].replace("℃","")
    tmp = ls.pop(1)
    tmp = ls.pop(5)
    return ls

proxies={
        'http' : 'http://127.0.0.1:7890',
        'https': 'http://127.0.0.1:7890'
}

def get_raw_info(url): # pass a url, get 7-days weather info, and storaged them in a matrix
    try:
        req = requests.get(url)
    except:
        req = requests.get(url,proxies=proxies)
    req.encoding = "utf-8"
    txt = req.text
    bs4obj    = BeautifulSoup(txt,"lxml")
    content0  = bs4obj.body.contents[7]
    city_name = content0.contents[1].contents[7].contents[0] # city's name
    weatherinfo = content0.contents[5].div.div # a bs4 tag obj which contains all weather info
    dayweaobj = weatherinfo.contents[3] # a bs4 tag object which contains 7-days weather info
    mx = []
    for i in range(0,7):
        mx.append(get_metadata(dayweaobj.contents[2*i+1]))
    return city_name,mx

def get_column_name(): # get column(date) names
    url  = "https://weather.cma.cn/web/weather/54511"
    res  = get_raw_info(url)
    mx   = res[1]
    mxdf = pd.DataFrame(mx)
    return np.array(mxdf[0],) #use these 2 scripts to get column names.

def format_info(code): # pass city code, return a list which contained formatted information(wea+temp)
    url = "https://weather.cma.cn/web/weather/"+str(code)
    res = get_raw_info(url)
    city_name = "{0:{1}<4}".format(res[0],chr(12288))
    mx  = res[1]
    ls  = []
    ls.append(city_name)
    for t in mx:
        weather = "{0:{1}>6}".format(t[1],chr(12288))  # t1: weather(day)
        temperature = "{0:<7}".format(t[4])            # t4: temperature
        ls.append("{} {}".format(weather,temperature))
    return ls

if(__name__=="__main__"):
    print("+-----------------------------------+")
    print("|          Weather Get V3.0         |")
    print("|   writtern by zwy at Oct 4, 2021  |")
    print("+-----------------------------------+")
    print("Get today's weather from https://weather.cma.cn/\n")
    print("Current date:",end="")
    print(datetime.datetime.now().strftime("%Y %m %d"))
    pred_days = 7 # how many days will we display?
    city_list=[
            ["哈尔滨",50953],
            ["沈阳",54342],
            ["北京",54511],
            ["天津",54517],
            ["兰州",52889],
            ["太原",53772],
            ["晋城",53976],
            ["郑州",57083],
            ["淮南",58224],
            ["信阳",57297],
            ["上海",58367],
            ["恩施",57447],
            ["温州",58659],
            ["武汉",57494],
            ["长沙",57679],
            ["广州",59287],
            ["湛江",59658],
            ["海口",59758]
            ]
    column = get_column_name()

    hr = "{0:{1}^8}".format("-","-") # split line
    for i in range(0,pred_days):
        hr += "{0:{1}^20}".format("-","-")

    print(hr)

    print("{0:{1}^4}".format("城市",chr(12288)),end="")
    for i in range(0,pred_days):
        print("{0:{1}>6}".format("",chr(12288)),end="")
        print("{0:<8}".format(column[i]),end="")
    print("")

    print(hr)

    for c in city_list:
        l = format_info(c[1])
        for j in range(0,pred_days+1):
            print(l[j],end="")
        print("")

    print(hr,"\n")




