# -*- coding: utf-8 -*-

# Copyright 2005-2006 Joe Wreschnig
#           2013 Christoph Reiter
#           2014 Ben Ockmore
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of version 2 of the GNU General Public License as
# published by the Free Software Foundation.

"""Read and write Vorbis comment data.

Vorbis comments are freeform key/value pairs; keys are
case-insensitive ASCII and values are Unicode strings. A key may have
multiple values.

The specification is at http://www.xiph.org/vorbis/doc/v-comment.html.
"""

import sys

import mutagenx
from ._compat import reraise, BytesIO, text_type, xrange, PY3, PY2, ord_
from mutagenx._util import cdata

from collections import MutableMapping, MutableSequence

def is_valid_key(key):
    """Return true if a string is a valid Vorbis comment key.

    Valid Vorbis comment keys are printable ASCII between 0x20 (space)
    and 0x7D ('}'), excluding '='.

    Takes str/unicode in Python 2, unicode in Python 3
    """

    if PY3 and isinstance(key, bytes):
        raise ValueError

    for c in key:
        if c < " " or c > "}" or c == "=":
            return False
    else:
        return bool(key)


istag = is_valid_key


class error(IOError):
    pass


class VorbisUnsetFrameError(error):
    pass


class VorbisEncodingError(error):
    pass


class VComment(mutagenx.Metadata, MutableSequence):
    """A Vorbis comment parser, accessor, and renderer.

    All comment ordering is preserved. A VComment is a list of
    key/value pairs, and so any Python list method can be used on it.

    Vorbis comments are always wrapped in something like an Ogg Vorbis
    bitstream or a FLAC metadata block, so this loads string data or a
    file-like object, not a filename.

    Attributes:

    * vendor -- the stream 'vendor' (i.e. writer); default 'MutagenX'
    """

    vendor = u"Mutagen " + mutagenx.version_string

    def __init__(self, data=None, *args, **kwargs):
        # Collect the args to pass to load, this lets child classes
        # override just load and get equivalent magic for the
        # constructor.
        self._internal = []

        if data is not None:
            if isinstance(data, bytes):
                data = BytesIO(data)
            elif not hasattr(data, 'read'):
                raise TypeError("VComment requires bytes or a file-like")
            self.load(data, *args, **kwargs)

    def __getitem__(self, index):
        return self._internal[index]

    def __setitem__(self, index, value):
        self._internal[index] = value

    def __delitem__(self, index):
        del self._internal[index]

    def __len__(self):
        return len(self._internal)

    def insert(self, index, value):
        self._internal.insert(index, value)

    def load(self, fileobj, errors='replace', framing=True):
        """Parse a Vorbis comment from a file-like object.

        Keyword arguments:

        * errors:
            'strict', 'replace', or 'ignore'. This affects Unicode decoding
            and how other malformed content is interpreted.
        * framing -- if true, fail if a framing bit is not present

        Framing bits are required by the Vorbis comment specification,
        but are not used in FLAC Vorbis comment blocks.
        """

        try:
            vendor_length = cdata.uint_le(fileobj.read(4))
            self.vendor = fileobj.read(vendor_length).decode('utf-8', errors)
            count = cdata.uint_le(fileobj.read(4))
            for i in xrange(count):
                length = cdata.uint_le(fileobj.read(4))
                try:
                    string = fileobj.read(length).decode('utf-8', errors)
                except (OverflowError, MemoryError):
                    raise error("cannot read %d bytes, too large" % length)
                try:
                    tag, value = string.split('=', 1)
                except ValueError as err:
                    if errors == "ignore":
                        continue
                    elif errors == "replace":
                        tag, value = u"unknown%d" % i, string
                    else:
                        reraise(VorbisEncodingError, err, sys.exc_info()[2])
                try:
                    tag = tag.encode('ascii', errors)
                except UnicodeEncodeError:
                    raise VorbisEncodingError("invalid tag name %r" % tag)
                else:
                    # string keys in py3k
                    if PY3:
                        tag = tag.decode("ascii")
                    if is_valid_key(tag):
                        self.append((tag, value))

            if framing and not bytearray(fileobj.read(1))[0] & 0x01:
                raise VorbisUnsetFrameError("framing bit was unset")
        except (cdata.error, TypeError):
            raise error("file is not a valid Vorbis comment")

    def validate(self):
        """Validate keys and values.

        Check to make sure every key used is a valid Vorbis key, and
        that every value used is a valid Unicode or UTF-8 string. If
        any invalid keys or values are found, a ValueError is raised.

        In Python 3 all keys and values have to be a string.
        """

        # be stricter in Python 3
        if PY3:
            if not isinstance(self.vendor, text_type):
                raise ValueError
            for key, value in self:
                if not isinstance(key, text_type):
                    raise ValueError
                if not isinstance(value, text_type):
                    raise ValueError

        if not isinstance(self.vendor, text_type):
            try:
                self.vendor.decode('utf-8')
            except UnicodeDecodeError:
                raise ValueError

        for key, value in self._internal:
            try:
                if not is_valid_key(key):
                    raise ValueError
            except:
                raise ValueError("%r is not a valid key" % key)

            if not isinstance(value, text_type):
                try:
                    value.decode("utf-8")
                except:
                    raise ValueError("%r is not a valid value" % value)
        else:
            return True

    def clear(self):
        """Clear all keys from the comment."""

        for i in list(self._internal):
            self._internal.remove(i)

    def write(self, framing=True):
        """Return a string representation of the data.

        Validation is always performed, so calling this function on
        invalid data may raise a ValueError.

        Keyword arguments:

        * framing -- if true, append a framing bit (see load)
        """

        self.validate()

        def _encode(value):
            if not isinstance(value, bytes):
                return value.encode('utf-8')
            return value

        f = BytesIO()
        vendor = _encode(self.vendor)
        f.write(cdata.to_uint_le(len(vendor)))
        f.write(vendor)
        f.write(cdata.to_uint_le(len(self)))
        for tag, value in self._internal:
            tag = _encode(tag)
            value = _encode(value)
            comment = tag + b"=" + value
            f.write(cdata.to_uint_le(len(comment)))
            f.write(comment)
        if framing:
            f.write(b"\x01")
        return f.getvalue()

    def pprint(self):

        def _decode(value):
            if not isinstance(value, text_type):
                return value.decode('utf-8', 'replace')
            return value

        tags = [u"%s=%s" % (_decode(k), _decode(v)) for k, v in self._internal]
        return u"\n".join(tags)

    def __eq__(self, other):
        if isinstance(other, VComment):
            return self._internal == other._internal
        else:
            return self._internal == other

    def __ne__(self, other):
        return not self.__eq__(other)

class VCommentDict(MutableMapping):
    """A VComment that looks like a dictionary.

    This object differs from a dictionary in two ways. First,
    len(comment) will still return the number of values, not the
    number of keys. Secondly, iterating through the object will
    iterate over (key, value) pairs, not keys. Since a key may have
    multiple values, the same value may appear multiple times while
    iterating.

    Since Vorbis comment keys are case-insensitive, all keys are
    normalized to lowercase ASCII.
    """

    def __init__(self, data=None, *args, **kwargs):
        self._internal = VComment()

        if data is not None:
            if isinstance(data, bytes):
                data = BytesIO(data)
            elif not hasattr(data, 'read'):
                raise TypeError("VComment requires bytes or a file-like")
            self.load(data, *args, **kwargs)

    def _get_vendor(self):
        return self._internal.vendor

    def _set_vendor(self, value):
        self._internal.vendor = value

    vendor = property(_get_vendor, _set_vendor)

    def __getitem__(self, key):
        """A list of values for the key.

        This is a copy, so comment['title'].append('a title') will not
        work.

        """

        if not is_valid_key(key):
            raise ValueError

        key = key.lower()

        values = [value for (k, value) in self._internal if k.lower() == key]
        if not values:
            raise KeyError(key)
        else:
            return values

    def __delitem__(self, key):
        """Delete all values associated with the key."""

        if not is_valid_key(key):
            raise ValueError

        key = key.lower()
        to_delete = [x for x in self._internal if x[0].lower() == key]

        if not to_delete:
            raise KeyError(key)
        else:
            for item in to_delete:
                self._internal.remove(item)

    def __setitem__(self, key, values):
        """Set a key's value or values.

        Setting a value overwrites all old ones. The value may be a
        list of Unicode or UTF-8 strings, or a single Unicode or UTF-8
        string.

        """

        if not is_valid_key(key):
            raise ValueError

        if not isinstance(values, list):
            values = [values]
        try:
            del(self[key])
        except KeyError:
            pass

        if PY2:
            key = key.encode('ascii')

        for value in values:
            self.append((key, value))

    def __eq__(self, other):
        if isinstance(other, (VComment, list)):
            return self._internal == other
        else:
            return self.as_dict() == other

    def __iter__(self):
        return iter({k.lower() for k,v in self._internal})

    def __len__(self):
        return len([k for k,v in self._internal])

    def as_dict(self):
        """Return a copy of the comment data in a real dict."""
        d = {}
        for key, value in self._internal:
            d.setdefault(key.lower(), []).append(value)
        return d

    # Wrapper functions to expose internal VComment functionality

    def load(self, fileobj, errors='replace', framing=True):
        self._internal.load(fileobj, errors, framing)

    def validate(self):
        return self._internal.validate()

    def clear(self):
        self._internal.clear()

    def write(self, framing=True):
        return self._internal.write(framing)

    def pprint(self):
        return self._internal.pprint()

    def index(self, value):
        return self._internal.index(value)

    def count(self, value):
        return self._internal.count(value)

    def insert(self, index, value):
        self._internal.insert(index, value)

    def append(self,value):
        self._internal.append(value)

    def reverse(self):
        self._internal.reverse()

    def extend(self, values):
        self._internal.extend(values)

    def remove(self, value):
        self._internal.remove(value)

    def __iadd__(values):
        self._internal.__iadd__(values)
        return self

    # The following VComment methods aren't wrapped, because they're
    # implemented in a dict-interface here.
    #
    #__getitem__, __setitem__, __delitem__, __len__
    #__contains__, __iter__, pop
