#!/usr/bin/python

# Copyright (c) 2013 Dropbox, Inc.
#
# 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.

from collections import defaultdict, namedtuple
import itertools
import textwrap
import sys
import os
import re

# Helper for flattening nested lists
flatten = itertools.chain.from_iterable

CodepointInfo = namedtuple("CodepointInfo",
    [ "codepoint", "name", "category", "ccc", "bidi_category", "decomposition",
      "decimal_value", "digit_value", "numeric_value", "mirrored", "old_name", "comment",
      "uppercase", "lowercase", "titlecase" ])

Decomposition = namedtuple("Decomposition", [ "type", "mapping" ])

# The highest possible codepoint is 0x10FFFF, so we need 21 bits to represent a codepoint.
UNICODE_CODE_SPACE_BITS = 21

def from_hex(s):
    """Parse a hex string.
    """
    return int(s, 16) if s else None


def file_lines(*path_components):
    """Helper for reading all lines out of a file, ignoring comments.
    """
    with open(os.path.join(*path_components)) as f:
        for line in f.readlines():
            line = line.strip().split("#", 1)[0]
            if line and line[0] != '@':
                yield line


def parse_data(base_path):
    """Parse the Unicode character data and composition exclusion files.
    """

    codepoints = {}
    for line in file_lines(base_path, "UnicodeData.txt"):
        fields = line.strip().split(";")

        if fields[5]:
            decomp_fields = fields[5].split(" ")
            if decomp_fields[0].startswith("<"):
                decomp = Decomposition(decomp_fields[0], map(from_hex, decomp_fields[1:]))
            else:
                decomp = Decomposition("canonical", map(from_hex, decomp_fields))
        else:
            decomp = Decomposition("none", None)

        info = CodepointInfo(
            from_hex(fields[0]), fields[1], fields[2], int(fields[3]), fields[4], decomp,
            fields[6], fields[7], fields[8], fields[9], fields[10], fields[11],
            from_hex(fields[12]), from_hex(fields[13]), from_hex(fields[14]))

        codepoints[info.codepoint] = info

    exclusions = set(map(from_hex, file_lines(base_path, "CompositionExclusions.txt")))

    return codepoints, exclusions


def parse_collation(base_path):
    """Parse the DUCET file allkeys.txt
    """
    collation_elements = {}
    def parse_element(el_string):
        # we treat * variable weight as non-ignorable because this is not actually used for sorting
        return map(from_hex, re.split('\.|\*',el_string))
    for line in file_lines(base_path, "allkeys.txt"):
        fields = line.strip().split(";");
        if fields[0]:
            codepoints = tuple(map(from_hex, fields[0].strip().split()))
            fields = re.split('\]\[(?:\.|\*)', fields[1].strip(' []*.'))
            collation_elements[codepoints] = map(parse_element, fields)
    return collation_elements