"""
Create a template app from ODM-formatted OpenClinica study metadata
"""
from lxml import etree
from django.core.management.base import BaseCommand
from corehq.apps.app_manager.models import (
    Application,
    Module,
    OpenCaseAction,
    UpdateCaseAction,
    PreloadAction,
    OpenSubCaseAction,
    FormActionCondition,
    CaseListForm,
)
from corehq.apps.app_manager.xform_builder import XFormBuilder
from custom.openclinica.const import (
    CC_SUBJECT_KEY,
    CC_STUDY_SUBJECT_ID,
    CC_DOB,
    CC_SEX,
    CC_ENROLLMENT_DATE,
)
from custom.openclinica.utils import odm_nsmap, quote_nan


# Map ODM data types to ODK XForm data types
# cf. http://www.cdisc.org/system/files/all/generic/application/octet-stream/odm1_3_0_final.htm#ItemDef
#     https://opendatakit.github.io/odk-xform-spec/#data-types
#     http://www.w3.org/TR/xmlschema-2/#built-in-primitive-datatypes
ODK_DATA_TYPES = {
    'text': 'string',
    'integer': 'int',
    'float': 'decimal',
    'date': 'date',
    'time': 'time',
    'datetime': 'dateTime',
    'string': 'string',
    'boolean': 'boolean',
    'double': 'decimal',
    'hexBinary': 'string',
    'base64Binary': 'string',
    'hexFloat': 'string',
    'base64Float': 'string',
    'partialDate': 'date',
    'partialTime': 'time',
    'partialDatetime': 'dateTime',
    'durationDatetime': 'string',
    'intervalDatetime': 'string',
    'incompleteDatetime': 'string',
    'URI': 'string',
    # Convert ODM questions with choices to XForm selects
    'select': 'select',
    'select1': 'select1',
}


class StudyMetadataError(Exception):
    pass


def get_odm_child(node, child_node):
    """
    Return a child node in ODM namespace. Assumes only one child node with that name, and that it will be there.

    >>> from lxml import etree
    >>> foo_node = etree.fromstring('''<?xml version="1.0" encoding="UTF-8"?>
    ... <foo xmlns="http://www.cdisc.org/ns/odm/v1.3">
    ...   <bar>baz</bar>
    ... </foo>''')
    >>> get_odm_child(foo_node, 'bar').text
    'baz'

    """
    try:
        return node.xpath('./odm:' + child_node, namespaces=odm_nsmap)[0]
    except IndexError:
        raise StudyMetadataError('"{}" tag is missing a "{}" child node'.format(node.tag, child_node))


class StudyObject(object):