#---------------------------------------------------------------------------
# Copyright 2014 The Open Source Electronic Health Record Agent
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License
 is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#---------------------------------------------------------------------------
import os
import sys
import re
from datetime import datetime
import logging
import glob
import cgi
import re
import json

FILE_DIR = os.path.dirname(os.path.abspath(__file__))
SCRIPT
S_DIR = os.path.normpath(os.path.join(FILE_DIR, "../../../Scripts"))
print SCRIPTS_DIR
if SCRIPTS_DIR not in sys.path:
  sys.path.append(SCRIPTS_DIR)

from ZWRGlobalParser import getKeys
from CrossReference import FileManField
from ZWRGlobalParser import readGlobalNodeFromZWRFileV2
from WebPageGenerator import getRoutineHtmlFileName, normalizePackageName
from WebPageGenerator import getPackageHtmlFileName
from FileManGlobalDataParser import FileManDataEntry, FileManDataField, FileManFileData
from DataTableHtml import data_table_list_init_setup
from DataTableHtml import data_table_large_list_init_setup, data_table_record_init_setup
from DataTableHtml import outputDataTableHeader, outputCustomDataTableHeader, outputDataTableFooter
from DataTableHtml import writeTableListInfo, outputDataListTableHeader
from DataTableHtml import outputLargeDataListTableHeader, outputDataRecordTableHeader
from DataTableHtml import outputFileEntryTableList, safeElementId


def test_sub():
  print data_table_large_list_init_setup.substitute(ajexSrc="Test", tableName="Test")
  print data_table_list_init_setup.substitute(tableName="Test")
  print data_table_record_init_setup.substitute(tableName="Test")

dox_url = "http://code.osehra.org/dox/"
def getDataEntryHtmlFile(dataEntry, ien, fileNo):
  entryName = str(dataEntry.name)
  return getDataEntryHtmlFileByName(entryName, ien, fileNo)

def getDataEntryHtmlFileByName(entryName, ien, fileNo):
  entryName = entryName[:20] # max 20 chars
  return ("%s-%s" % (fileNo, ien)) + ".html"

def getFileHtmlLink(dataEntry, value, **kargs):
  entryName = str(value)
  htmlFile = getDataEntryHtmlFileByName(entryName, dataEntry.ien,
                                        dataEntry.fileNo)
  entryDescription=''
  if '1' in dataEntry.fields:
    if isinstance(dataEntry.fields['1'].value, list):
      for line in dataEntry.fields['1'].value:
        entryDescription += ' ' + cgi.escape(line).replace('"', r"&quot;").replace("'", r"&quot;")
  return "<a title=\"%s\" href=\"../%s/%s\">%s</a>" % (entryDescription, dataEntry.fileNo.replace(".","_"),htmlFile, value)

def getRoutineName(inputString):
  tagRoutine = inputString.split('^')
  if len(tagRoutine) == 1:
    return inputString
  else:
    return tagRoutine[-1]

def getRoutineHRefLink(dataEntry, routineName, **kargs):
  rtnName = getRoutineName(routineName)
  crossRef = None
  if 'crossRef' in kargs:
    crossRef = kargs['crossRef']
    if crossRef and not crossRef.getRoutineByName(rtnName):
      return routineName
  pos = routineName.find(rtnName)
  return routineName[:pos] + "<a href=\"%s%s\">%s</a>" % (dox_url,
                                      getRoutineHtmlFileName(rtnName),
                                      rtnName) + routineName[pos+len(rtnName):]

def getPackageHRefLink(pkgName):
  value = "<a href=\"%s%s\">%s</a>" % (dox_url,
                                       getPackageHtmlFileName(pkgName),
                                       pkgName)
  return value

def getWordProcessingDataBrief(dataEntry, value, **kargs):
  return getWordProcessingData(value, False)

def getWordProcessingData(value, isList=True):
  outValue = " ".join(value)
  if isList:
    outValue = "<pre>\n" + cgi.escape(outValue) + "\n</pre>\n"
  return outValue

def getFileManFilePointerLink(dataEntry, value, **kargs):
  if value:
    fields = value.split('^')
    if len(fields) == 3: # fileNo, ien, name
      refFile = getDataEntryHtmlFileByName(fields[2], fields[1], fields[0])
      value = '<a href="../%s/%s">%s</a>' % (fields[0].replace(".","_"),refFile, fields[-1])
    elif len(fields) == 2:
      value = 'File: %s, IEN: %s' % (fields[0], fields[1])
    else:
      logging.error("Unknown File Pointer Value %s" % value)
  return value

""" Requires extra information to be made available on the run of the object.

    ("HL7 Type Tag", '1/.01', "771.2/.01" ,getFreeTextLink), # Action Tag

    In addition to the current file's location, found in entry 1, add the place
    where the information is available in the target file as part of the second entry.
    "{File Number}/{Field Number}"

"""
def getFreeTextLink(dataEntry, value, **kargs):
  if value:
    if 'glbData' in kargs:
      glbData = kargs['glbData']
      # Acquire the field and file of the target information
      file,field = kargs["targetField"].split("/");
      # Check if the target file hasn't already been parsed
      if file not in glbData.outFileManData.keys():
        glbData._glbData[file] = FileManFileData(file,
                                  glbData.getFileManFileNameByFileNo(file))
        pathName = glbData._allFiles[file]["path"]
        # Taken from the FileManGlobalDataParser
        glbData._createDataRootByZWRFile(pathName)
        glbLoc = glbData._glbLocMap.get(file)
        for dataRoot in readGlobalNodeFromZWRFileV2(pathName, glbLoc):
          if not dataRoot:
            continue
          glbData._dataRoot = dataRoot
          fileDataRoot = dataRoot
          glbData._parseDataBySchema(fileDataRoot, glbData._allSchemaDict[file],
                                  glbData._glbData[file])
      # Once the information is available check for the target in any available information in that file
      for entry in glbData.outFileManData[file].dataEntries:
        if value == glbData.outFileManData[file].dataEntries[entry].fields[field].value:
          return '<a href="../%s/%s-%s.html">%s</a>' % (glbData.outFileManData[file].dataEntries[entry].fileNo.replace(".","_"),file,entry, glbData.outFileManData[file].dataEntries[entry].fields[field].value)
  return value

"""
fields and logic to convert to html for RPC List
"""
rpc_list_fields = (
       ("Name", '.01', getFileHtmlLink), # Name
       ("Tag", '.02', None), # Tag
       ("Routine", '.03', getRoutineHRefLink), # Routine
       ("Availability", '.05', None),# Availability
       #("Description", '1', getWordProcessingDataBrief),# Description
   )

"""
fields and logic to convert to html for HL7 List
"""
hl7_list_fields = (
       ("Name", '.01', getFileHtmlLink), # Name
       ("Type", '4', None), # Type
       ("Transaction Message Type", '770.3', getFileManFilePointerLink), # Message Type
       ("Response Message Type", '770.11', getFileManFilePointerLink), # Message Type
       ("Event Type", '770.4', getFileManFilePointerLink), # Event Type
       ("Sender", '770.1', getFileManFilePointerLink),# Sending Application
       ("Receiver", '770.2', getFileManFilePointerLink),# Receiving Application
   )

hl7_table_header_fields = (
    ("""
      <th rowspan="2">Name</th>
      <th rowspan="2">Type</th>
      <th colspan="2">Message Type</th>
      <th rowspan="2">Event Type</th>
      <th rowspan="2">Sender</th>
      <th rowspan="2">Receiver</th>
     """),
    ("""
      <th>Transaction</th>
      <th>Response</th>
     """),
  )

hl7_column_names = ["Name", "Type", "Transaction","Response",
                    "Event Type", "Sender", "Receiver"]

"""
fields and logic to convert to html for Protocol List
"""
protocol_list_fields = (
       ("Name", '.01', getFileHtmlLink), # Name
       ("Type", '4', None), # Type
       ("Lock", '3', None), # Type
       ("Description", '3.5', None), # Type
       ("Entry Actio