# coding: utf-8

"""
Gencfg tag representation
"""

from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals

import re
import six

from functools import total_ordering

from .errors import InvalidTag


@total_ordering
class GencfgTag(object):
    _VALIDATION_REGEXP = re.compile(r'.*(?P<tag>stable-(?P<release>[1-9]\d{0,3})-r(?P<revision>[1-9]\d{0,4}))$')

    def __init__(self, tag):
        if isinstance(tag, GencfgTag):
            self._tag = tag.tag
            self._release = tag.release
            self._revision = tag.revision
        else:
            if tag is None or tag == 'trunk':
                self._tag = 'trunk'
                self._release = None
                self._revision = None
            else:
                parsed = self._VALIDATION_REGEXP.match(tag)
                if parsed:
                    self._tag = parsed.group('tag')
                    self._release = int(parsed.group('release'))
                    self._revision = int(parsed.group('revision'))
                else:
                    raise InvalidTag('"{}" is not valid gencfg tag'.format(tag))

    def __nonzero__(self):
        return self.__bool__()

    def __bool__(self):
        return True if self._release and self._revision else False

    def __hash__(self):
        return hash((self._release, self._revision))

    @property
    def tag(self):
        return self._tag

    @property
    def release(self):
        return self._release

    @property
    def revision(self):
        return self._revision

    def __eq__(self, other):
        if isinstance(other, six.string_types):
            return self == GencfgTag(other)
        else:
            return self.tag == other.tag

    def __ge__(self, other):
        if other.tag == 'trunk' and self.tag != 'trunk':
            return False
        else:
            return self.tag == 'trunk' or self.release > other.release or (self.release == other.release and self.revision >= other.revision)

    def __repr__(self):
        return self.tag
