#!/usr/bin/xvfb-run python
# -*- coding: utf-8 -*-

### PYTHON

from datetime import *

import random
import time

import logging
FORMAT = '%(asctime)s %(levelname)s %(message)s'
logging.basicConfig(format=FORMAT, level=logging.INFO)

import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'ntuh.settings'

import six
if six.PY2:
    import sys
    reload(sys)  # Reload does the trick!
    sys.setdefaultencoding('utf8')

### PUBLIC

from dateutil.relativedelta import *
from django.db.models import *

import django
django.setup()

### PRIVATE

# from ntuhgov import xportal
from ntuhgov.portal_selenium import Login, ReportPathology, CTMR
from registry.models import *


def main():

    req_no_of_random_items = 13

    qs = PathologyReport.objects.all()
    possible_ids = list(qs.values_list('PersonID', flat=True))        
    possible_ids = random.choices(possible_ids, k=req_no_of_random_items)

    SECONDS_LEFT = 300

    for PersonID in possible_ids:
        seconds = random.randint(0, SECONDS_LEFT)
        logging.info((PersonID, 'sleep', seconds, 'of', SECONDS_LEFT))
        SECONDS_LEFT -= seconds
        time.sleep(seconds)
        reports = CTMR(PersonID)
        for r in reports:
            p, created = XrayTextReport.objects.get_or_create(ReportKey = r['ReportKey'])

            p.ChartNo    = r['ChartNo']
            p.ReportKey  = r['ReportKey']
            p.ReportCode = r['ReportCode']
            p.PersonID   = r['PersonID']

            p.OrderDesc  = r['OrderDesc']
            p.ExamDate   = r['ExamDate'].replace('/', '-').split(' ')[0]
            if '*' not in r['ReportDate']:
                p.ReportDate = r['ReportDate'].replace('/', '-').split(' ')[0]

            p.Impression = r['Impression']
            logging.info(p.__dict__)

            p.Exam       = r['Exam']

            p.url        = r['url']
            p.html       = r['html']

            p.save()


if __name__ == '__main__':
    main()
