#coding=utf-8

import requests
import datetime

def get_data_sheet():
    url = "http://anoms.top/weather_get_v4.0/weather_get_for_server_v4.0_output.tsv" # 从ANOMS服务器上下载数据。爬虫程序在服务器上跑。或许这就是server-client模式的优点了吧。
    req = requests.get(url)
    req.encoding = 'utf-8'
    txt = req.text
    return txt

def data_format(text):
    ls    = text.split("\n")
    time  = ls[0]
    mx    = []
    index = {}
    for i in range(len(ls)):
        line = ls[i]
        if("#" not in line):
            a = line.split("\t")
            try:
                index[a[0]] = i
            except:
                pass
            mx.append(a)
    return time,mx,index

def get_column_name(line): # get column(date) names from a row in the data sheet.
    cn = []
    for i in range(2,len(line),8):
        cn.append(line[i])
    return cn


def format_info(data,index,code): # pass city code, return a list which contained formatted information(wea+temp)
    res = data[index[str(code)]-1] #我也不知道为什么要减1，反正这里减1就对了。
    city_name = "{0:{1}<7}".format(res[1],chr(12288))
    ls  = []
    ls.append(city_name)
    for i in range(3,len(res),8):
        weather = '{0:{1}>6}'.format(res[i],chr(12288))
        temperature = '{0:<7}'.format(res[i+3])
        ls.append("{} {}".format(weather,temperature))
    return ls

if(__name__=="__main__"):
    print("+-----------------------------------+")
    print("|          Weather Get V4.0         |")
    print("|   writtern by zwy on Nov 7, 2021  |")
    print("+-----------------------------------+")
    print("Getting today's weather from ANOMS server\nWhich got weather data from https://weather.cma.cn\n")
    print("Current date:",end="")
    print(datetime.datetime.now().strftime("%Y %m %d"))
    time,mx,index = data_format(get_data_sheet())
    print("Weather data was refreshed at {}".format(time.replace("#","")))
    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(mx[2])

    hr = "{0:{1}^14}".format("-","-") # split line
    for i in range(0,pred_days):
        hr += "{0:{1}^20}".format("-","-")

    print(hr)

    print("{0:{1}^7}".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(mx,index,c[1])
        #print(l)
        for j in range(0,pred_days+1):
            print(l[j],end="")
        print("")

    print(hr,"\n")
    
#TODO:
#在后续的更新中，希望添加以下功能：
#1. 爬取数据时，保存国家和省的名称。
#2. 支持按城市名称查询天气，使用模糊匹配算法（需要查一下）进行候选城市的筛选。


