# Path: mod/models/nic_cache.py
# class NicCache(Base):
#     __tablename__ = 'nic'
#     cardnum = Column(Integer, primary_key=True)
#     text = Column(String(1024))
#     date = Column(Integer, nullable=False)


from config import *
from tornado.httpclient import HTTPRequest, AsyncHTTPClient, HTTPClient
from bs4 import BeautifulSoup
from ..models.nic_cache import NicCache
from sqlalchemy.orm.exc import NoResultFound
from time import time
import tornado.web
import tornado.gen
import urllib, re
import json, base64


class NICHandler(tornado.web.RequestHandler):

    @property
    def db(self):
        return self.application.db

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

    @tornado.web.asynchronous
    @tornado.gen.engine
    def post(self):
        cardnum = self.get_argument('cardnum')
        data = {
            'username':cardnum,
            'password':self.get_argument('password'),
        }
        retjson = {'code':200, 'content':''}

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

# Path: mod/models/nic_cache.py
# class NicCache(Base):
#     __tablename__ = 'nic'
#     cardnum = Column(Integer, primary_key=True)
#     text = Column(String(1024))
#     date = Column(Integer, nullable=False)


# Path: mod/nic/handler.py
from config import *
from tornado.httpclient import HTTPRequest, AsyncHTTPClient, HTTPClient
from bs4 import BeautifulSoup
from ..models.nic_cache import NicCache
from sqlalchemy.orm.exc import NoResultFound
from time import time
import tornado.web
import tornado.gen
import urllib, re
import json, base64



class NICHandler(tornado.web.RequestHandler):

    @property
    def db(self):
        return self.application.db

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

    @tornado.web.asynchronous
    @tornado.gen.engine
    def post(self):
        cardnum = self.get_argument('cardnum')
        data = {
            'username':cardnum,
            'password':self.get_argument('password'),
        }
        retjson = {'code':200, 'content':''}

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

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