# coding:utf-8

"""A script to query leftover amount of money on Shenzhen Tong card.
Maybe I will consider buying one nfc interface and do something more like funding.
"""

import re
from sys import argv
from urllib import urlencode
from urllib2 import Request, urlopen


api = 'http://query.shenzhentong.com:8080/sztnet/qryCard.do'
headers = {
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
    'Accept-Encoding': 'gzip, deflate',
    'Cache-Control': 'no-cache',
    'Connection': 'close',
    'Content-Type': 'application/x-www-form-urlencoded',
    'Host': 'query.shenzhentong.com:8080',
    'Origin': 'http://query.shenzhentong.com:8080',
    'Pragma': 'no-cache',
    'Referer': 'http://query.shenzhentong.com:8080/sztnet/qryCard.do',
    'Upgrade-Insecure-Requests': '1',
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36'
}


def query(cardno):
    data = {'cardno': cardno}
    req = Request(api, headers=headers, data=urlencode(data))
    response = urlopen(req)
    html = response.read()
    block = re.findall(r'class=\'tableact\'.*?\<\/table\>', html)
    if block is not None:
        data = block[0]
        left = re.findall(r'\d+\.\d+', data)
        if left is not None:
            card_info = {}
            card_info.update({'cardno': cardno})
            card_info.update({'amount': left[0]})
            updates = re.findall(r'\d{4}-\d{2}-\d{2}\ \d{2}:\d{2}:\d{2}', data)
            update_time = updates[0] if updates else None
            card_info.update({'update': update_time})
            expires = re.findall(r'(?<=\>)\d{4}-\d{2}-\d{2}', data)
            expire_time = expires[0] if expires else None
            card_info.update({'expire': expire_time})
            return card_info
    return query(cardno)


if __name__ == '__main__':
    cards = argv[1:]
    if len(cards) == 0:
        raise RuntimeError('Invalid number of card number!')
        # cardno = '665220724'
        # cards.append(cardno)
    for cardno in cards:
        print query(cardno)
