#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2012-2018, CRS4
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
# the Software, and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

import sys
import os
import re
import pprint
from optparse import OptionParser
from lxml import objectify, etree
import collections

try:
    import cPickle as pickle
except ImportError:
    import pickle


class ProfileParser(object):

    def __init__(self, input_path, output_path):
        self.input_path = input_path
        self.output_path = output_path
        self.parse_profiles()

    def _sanitize(self, s):
        if s is not None:
            s = s.strip().upper()
            s = re.sub("\W+", "_", s)
            if s.endswith('_'):
                s = s[:-1]
            if s.startswith('_'):
                s = s[1:]
            m = re.match("^(C[MNKQ])(_[A-Z]+\d*){1,}(_\d+){0,}$", s)
            if m is not None:
                s = re.sub("_\d+$", "", s)
                s = s[2:].replace("_", "")
                s += m.groups()[2] or ''
        return s

    def _get_cardinality(self, obj):
        min_card = obj.get('Min') if obj.get('Min') is not None else 0
        max_card = obj.get('Max') if obj.get('Max') is not None else -1
        if max_card == "*":
            max_card = -1
        if obj.get('Usage') == "X":
            min_card = max_card = 0
        elif obj.get('Usage') == "R":
            min_card = 1
        min_card = int(min_card)
        max_card = int(max_card)

        return min_card, max_card

    def _parse_children(self, parent, parent_name):
        children = []
        for child in parent.getchildren():
            child_name = child.get('Name')
            cardinality = self._get_cardinality(child)
            if child.tag == 'Segment':
                segment_children = self._parse_segment(child)
                children.append((child_name, ('sequence', segment_children), cardinality, 'SEG'))
            elif child.tag == 'SegGroup':
                group_name = "{}_{}".format(parent_name, child_name)
                group_children = self._parse_children(child, parent_name)
                children.append((group_name, ('sequence', group_children), cardinality, 'GRP'))
        return tuple(children)

    def _parse_segment(self, segment):
        name = segment.get('Name')
        fields = []
        for index, field in enumerate(segment.Field):
            field_name = "{}_{}".format(name, index + 1)
            field_long_name = self._sanitize(field.get('Name'))
            field_datatype = field.get('Datatype')
            field_cardinality = self._get_cardinality(field)
            field_length = int(field.get('Length')) if field.get('Length') else 0
            field_table = "HL7{}".format(field.get('Table')) if field.get('Table') else None
            field_children = self._parse_datatype(field) or None
            field_type = 'sequence' if field_children is not None else 'leaf'
            field_datatype = field_datatype.upper() if field_datatype.upper() != "VARIES" else "varies"
            field_data = [field_name, (field_type, field_children, field_datatype,
                                       field_long_name, field_table, field_length),
                          field_cardinality, "FIE"]
            fields.append(tuple(field_data))

        return tuple(fields)

    def _parse_datatype(self, parent):
        components = []
        datatype = parent.get('Datatype')
        for el_type in ['Component', 'SubComponent']:
            try:
                for c_index, component in enumerate(getattr(parent, el_type)):
                    comp_name = "{}_{}".format(datatype, c_index + 1)
                    comp_long_name = self._sanitize(component.get('Name'))
                    comp_cardinality = (1, 1) if component.get('Usage') in ('R',) else (0, 1)
                    comp_datatype = component.get('Datatype')
                    comp_length = int(component.get('Length')) if component.get('Length') else 0
                    comp_table = "HL7{}".format(component.get('Table')) if component.get('Table') else None
                    comp_children = self._parse_datatype(component) or None
                    comp_type = 'sequence' if comp_children is not None else 'leaf'
                    comp_datatype = comp_datatype.upper() if comp_datatype.upper() != "VARIES" else "varies"
                    component_data = (comp_name, (comp_type, comp_children, comp_datatype,
                                                  comp_long_name, comp_table, comp_length),
                                      comp_cardinality, "CMP")
                    components.append(component_data)
            except:
                continue

        return tuple(components)

    def parse_profiles(self):
        try:
            if not os.path.exists(self.output_path):
                os.mkdir(self.output_path)
        except Exception as ex:
            print("Error occurred while saving the output to: ", self.output_path, ex)
            sys.exit(1)

        if os.path.isdir(self.input_path):
            files = [os.path.abspath(os.path.join(self.input_path, f)) for f in os.listdir(self.input_path)
                     if f.endswith('.xml')]
        elif os.path.isfile(self.input_path):
            files = [os.path.abspath(self.input_path)]
        else:
            return
        for f in files:
            filename, ext = os.path.splitext(os.path.basename(f))
            content = self.parse_profile(f)
            file_path = os.path.join(self.output_path, filename)
            with open(file_path, "wb") as output_file:
                pickle.dump(dict(content), output_file, protocol=2)

    def parse_profile(self, profile_file):
        """
        Parses the given message profile file using the lxml library then returns a dictionary
        containing parsing results.
        """
        elements = {}
        try:
            schema_path = os.path.join(self.input_path, profile_file)
            with open(schema_path, 'rb') as xml_file:
                data = xml_file.read()
        except Exception as ex:
            print("Error occurred while opening the message profile file")
            sys.exit(1)

        try:
            f = objectify.XML(data)
        except Exception as ex:
            import traceback
            traceback.print_exc()
            print("Invalid XML file: " + profile_file)
            sys.exit(1)
        print(type(f))
        message_structure = f.HL7v2xStaticDef.get('MsgStructID')
        print(message_structure)
        messages = collections.defaultdict(list)

        children = self._parse_children(f.HL7v2xStaticDef, message_structure)
        messages[message_structure] = ('sequence', children)

        return messages


if __name__ == '__main__':
    usage = "%prog [options] input_path\ninputh_path can be a file or a folder containing the message " \
            "profiles files"
    example = "Example: python profile_parser.py /home/user/ihe_2_3_folder"
    parser = OptionParser(usage=usage, epilog=example)
    parser.add_option("-o", "--output_dir",
                      action="store", dest="output_dir", default="./profile",
                      help="output path [%default]")
    (options, args) = parser.parse_args()
    try:
        path = args[0]
    except IndexError:
        parser.error("Please specify a message profile file or a folder containing message profile files.")
    else:
        if not os.path.isdir(path) and os.path.isdir(path):
            parser.error("Path %s not found." % path)
        ProfileParser(path, options.output_dir)
