# Path: mod/models/card_cache.py
# class CardCache(Base):
#     __tablename__ = 'card'
#     cardnum = Column(BIGINT, primary_key=True)
#     text = Column(LONGTEXT)
#     date = Column(Integer, nullable=False)
# 
# Path: mod/auth/handler.py
# def authApi(username,password):
#     data = {
#             'username':username,
#             'password':password
#         }
#     result = {'code':200,'content':''}
#     try:
#         client = HTTPClient()
#         request = HTTPRequest(
#             CHECK_URL,
#             method='POST',
#             body=urllib.urlencode(data),
#             validate_cert=False,
#             request_timeout=TIME_OUT)
#         response = client.fetch(request)
#         header = response.headers
#         if 'Ssocookie' in header.keys():
#             headertemp = json.loads(header['Ssocookie'])
#             cookie = headertemp[0]['cookieName']+"="+headertemp[0]['cookieValue']
#             cookie += ";"+header['Set-Cookie'].split(";")[0]
#             result['content'] = cookie
#         else:
#             result['code'] = 400
#     except HTTPError as e:
#         if e.code == 401:
#           result['code'] = 401
#         else:
#           result['code'] = 500
#     except Exception,e:
#         result['code'] = 500
#     return result


from config import *
from tornado.httpclient import HTTPRequest, AsyncHTTPClient
from BeautifulSoup import BeautifulSoup
from ..models.card_cache import CardCache
from sqlalchemy.orm.exc import NoResultFound
from time import time
from ..auth.handler import authApi
import tornado.web
import tornado.gen
import urllib, re
import json, base64
import datetime
import traceback
import requests
    def db(self):
        return self.application.db
    def on_finish(self):
        self.db.close()

    def get(self):
        self.write('Herald Web Service')

    @tornado.web.asynchronous
    @tornado.gen.engine
    def post(self):
        timedelta = int(self.get_argument('timedelta', default=0))
        # if int(timedelta)>7:
        #     timedelta = 7
        cardnum = self.get_argument('cardnum')
        data = {
            'Login.Token1':cardnum,
            'Login.Token2':self.get_argument('password'),
        }
        retjson = {'code':200, 'content':''}

        # read from cache
        try:
            status = self.db.query(CardCache).filter( CardCache.cardnum ==  cardnum ).one()
            if int(timedelta) == 0 and status.date > int(time())-600:
                self.write(base64.b64decode(status.text))
                self.db.close()
                self.finish()
                return
        except NoResultFound:

# Path: mod/models/card_cache.py
# class CardCache(Base):
#     __tablename__ = 'card'
#     cardnum = Column(BIGINT, primary_key=True)
#     text = Column(LONGTEXT)
#     date = Column(Integer, nullable=False)
# 
# Path: mod/auth/handler.py
# def authApi(username,password):
#     data = {
#             'username':username,
#             'password':password
#         }
#     result = {'code':200,'content':''}
#     try:
#         client = HTTPClient()
#         request = HTTPRequest(
#             CHECK_URL,
#             method='POST',
#             body=urllib.urlencode(data),
#             validate_cert=False,
#             request_timeout=TIME_OUT)
#         response = client.fetch(request)
#         header = response.headers
#         if 'Ssocookie' in header.keys():
#             headertemp = json.loads(header['Ssocookie'])
#             cookie = headertemp[0]['cookieName']+"="+headertemp[0]['cookieValue']
#             cookie += ";"+header['Set-Cookie'].split(";")[0]
#             result['content'] = cookie
#         else:
#             result['code'] = 400
#     except HTTPError as e:
#         if e.code == 401:
#           result['code'] = 401
#         else:
#           result['code'] = 500
#     except Exception,e:
#         result['code'] = 500
#     return result


# Path: mod/card/newhandler.py
from config import *
from tornado.httpclient import HTTPRequest, AsyncHTTPClient
from BeautifulSoup import BeautifulSoup
from ..models.card_cache import CardCache
from sqlalchemy.orm.exc import NoResultFound
from time import time
from ..auth.handler import authApi
import tornado.web
import tornado.gen
import urllib, re
import json, base64
import datetime
import traceback
import requests

    def db(self):
        return self.application.db
    def on_finish(self):
        self.db.close()

    def get(self):
        self.write('Herald Web Service')

    @tornado.web.asynchronous
    @tornado.gen.engine
    def post(self):
        timedelta = int(self.get_argument('timedelta', default=0))
        # if int(timedelta)>7:
        #     timedelta = 7
        cardnum = self.get_argument('cardnum')
        data = {
            'Login.Token1':cardnum,
            'Login.Token2':self.get_argument('password'),
        }
        retjson = {'code':200, 'content':''}

        # read from cache
        try:
            status = self.db.query(CardCache).filter( CardCache.cardnum ==  cardnum ).one()
            if int(timedelta) == 0 and status.date > int(time())-600:
                self.write(base64.b64decode(status.text))
                self.db.close()
                self.finish()
                return
        except NoResultFound:

            status = CardCache(cardnum=cardnum, text='*', date=int(time()))