# -*- coding: utf-8 -*-
#
# Copyright 2013 Simone Campagna
#
# 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.
#

"""\
Implementation of the 'dots' Serializer.
"""

import re

from .flat_serializer import FlatSerializer

__author__ = "Simone Campagna"
__copyright__ = 'Copyright (c) 2015 Simone Campagna'
__license__ = 'Apache License Version 2.0'
__all__ = [
    'join_dots_key',
    'normalize_dots_key',
    'split_dots_key',
    'DotsSerializer',
]


def join_dots_key(key_tuple):
    """Join key tuple to 'dots' key

       Parameters
       ----------
       key_tuple: key_tuple
           tuple of key tokens

       Returns
       -------
       str
           fully-qualified 'dots' key
    """
    return '.'.join(key_tuple)


def split_dots_key(key):
    """Split 'dots' key to key tuple

       Parameters
       ----------
       key: str
           fully-qualified 'dots' key

       Returns
       -------
       tuple
           tuple of key tokens
    """
    key = normalize_dots_key(key)
    if key:
        return tuple(key.split("."))  # pylint: disable=no-member
    else:
        return ()


_RE_NORMALIZE = re.compile(r'((?<=/)/+|/+$)')


def normalize_dots_key(key):
    """Normalize fully-qualified 'dots' key

       Parameters
       ----------
       key: str
           fully-qualified 'dots' key

       Returns
       -------
       str
           normalized key
    """
    return _RE_NORMALIZE.sub('', key.strip())


class DotsSerializer(FlatSerializer):
    "Dots serializer"

    @classmethod
    def class_tag(cls):
        return "dots"

    def _fqtuple2fqkey(self, fqtuple):
        return join_dots_key(fqtuple)

    def _fqkey2fqtuple(self, fqkey):
        return split_dots_key(fqkey)
