# coding=UTF-8
import requests
import xml.etree.ElementTree as ET

class weather:

    ns = '{urn:cwb:gov:tw:cwbcommon:0.1}'

    def __init__(self, id):
        self.id = id
        self.root = self.xml_url(id)

    def helper(self):
        dataset = self.root.find('{}dataset'.format(self.ns))
        parameterSet = dataset.find('{}parameterSet'.format(self.ns))
        parameter = parameterSet.findall('{}parameter'.format(self.ns))
        parameterValue = parameter[2].find('{}parameterValue'.format(self.ns))
        return parameterValue.text

    def uv(self, loactionCode):
        dataset = self.root.find('{}dataset'.format(self.ns))
        weatherElement = dataset.find('{}weatherElement'.format(self.ns))
        location = weatherElement.findall('{}location'.format(self.ns))
        for location in location:
            locationCode = location.find('{}locationCode'.format(self.ns))
            value = location.find('{}value'.format(self.ns))
            if locationCode.text == loactionCode:
                return value.text
        return "Can't find location code."

    @staticmethod
    def xml_url(id):
        url = "http://opendata.cwb.gov.tw/opendataapi"
        querystring = {"dataid":"{}".format(id), "authorizationkey":"CWB-0C91CFCC-BCBC-426C-992C-6582EAF9159F"}
        response = requests.request("GET", url, params=querystring)
        
        root = ET.fromstring(response.text.encode('utf-8')) 
        return root

# for parameterValue in root.iter('{}parameterValue'.format(ns)):
#     print(parameterValue.text)

if __name__ == "__main__":
    # 天氣小幫手 F-C0032-010 紫外線 O-A0005-001
    # http://opendata.cwb.gov.tw/opendataapi?dataid=O-A0005-001&authorizationkey=CWB-0C91CFCC-BCBC-426C-992C-6582EAF9159F
    helper = weather('F-C0032-010')
    a = weather.helper(helper)
    print(a)
    uvRay = weather('O-A0005-001')
    b = weather.uv(uvRay, '466920')
    print(b)