#!/usr/bin/env python
# -*- coding: utf8 -*-

import sys
import os
import re
import json
from collections import defaultdict
from datetime import datetime

from fmqlutils.cacher.cacherUtils import metaOfVistA
from fmqlutils.reporter.reportUtils import MarkdownTable, reportPercent, reportAbsAndPercent

from ..webReportUtils import SITE_DIR_TEMPL, TOP_MD_TEMPL, ensureWebReportLocations

"""
Background:
- Institutions: https://www.va.gov/directory/Guide/fac_list_by_state.cfm?State=OH&dnum=All
... and note that it seems that the default institution IEN from KSP == station number
in all cases.
"""

TEMPL = """## Introduction

Today the Veterans Administration (VA) provides and manages veteran care using <span style='yellowIt'>130</span> deployments of their in-house VistA system. Each VistA is an integrated suite of over one hundred applications sharing a single hierarchal database, FileMan. In deployed VistAs, FileMan holds up to <span style='yellowIt'>2 billion</span> interlinked records of over <span style='yellowIt'>4000</span> different types.

As well as the vast majority of Veteran clinical data, FileMan holds profiles of VA users, financial information, connected device descriptions, interface definitions and usage logs. The integrated and comprehensive nature of FileMan data makes it an ideal target for analysis to inform the migration of veteran care from VistA and into EHRM.

This __\"VistA by the Numbers\"__ report is one of a series, each of which captures the activity of a specific active VA VistA system. Each is generated by a framework for VistA analytics that first caches relevant data from a FileMan and then generates appropriate system descriptions. Such automation ensures common criteria for analysis and the ability to cover all <span style='yellowIt'>130</span> systems deployed in VA even as additional criteria are added to the framework over time.

This report describes __{}__  VistA with station number __{}__. Specifically, it describes a clone cut on __{}__ and housed in the VAEC.

"""

def webReportIntro(stationNo):
    
    meta = metaOfVistA(stationNo)
    
    title = "{} Introduction".format(stationNo)
    mu = TOP_MD_TEMPL.format(title)
    
    mu += TEMPL.format(
        meta.get("name", "VistA"),
        stationNo,
        meta["cutDate"]
    )
    
    mu += "Other defining properties of this clone are ...\n\n"
    
    tbl = MarkdownTable([":Property", ":Value"], includeNo=False)
    for metaPropInfo in [
        ("longName", "Full Name"),
        ("name", "Short Name"),
        ("dateEnteredPostMaster", "Post Master Entered"),
        ("lastSignOnPostMaster", "Post Master Last signon"),
        ("domainName", "Domain Name"),
        ("cio", "CIO"),
        ("iso", "ISO"),
    ]:
        if metaPropInfo[0] not in meta:
            continue
        val = meta[metaPropInfo[0]]
        if isinstance(val, dict):
            val = f'{val["label"]} [{val["id"].split("-")[1]}]'
        tbl.addRow([
            "__{}__".format(metaPropInfo[1]), 
            val
        ])
    if "nameFirstInstall" in meta:
        tbl.addRow([
            "__First Installed Build__",
            "{} ({})".format(meta["nameFirstInstall"], meta["dateLoadedFirstInstall"])
        ])
    mu += tbl.md() + "\n\n"
    
    userSiteDir = SITE_DIR_TEMPL.format(stationNo)
    open(userSiteDir + "intro.md", "w").write(mu)
    
# ################################# DRIVER #######################
               
def main():

    assert sys.version_info >= (3, 6)

    try:
        stationNo = sys.argv[1]
    except IndexError:
        raise SystemExit("Usage _EXE_ STATIONNO")

    ensureWebReportLocations(stationNo)

    webReportIntro(stationNo)
    
if __name__ == "__main__":
    main()
