# coding: utf-8

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

from six import integer_types
from humanfriendly import parse_size, format_size


class ByteSize(object):
    __slots__ = ('_value', )

    def __init__(self, value=0):
        self._value = value

    @classmethod
    def parse(cls, string, force_binary=False):
        return cls(parse_size(string, force_binary))

    def __eq__(self, other):
        if isinstance(other, ByteSize):
            return self._value == other._value
        else:
            return NotImplemented

    def __lt__(self, other):
        if isinstance(other, ByteSize):
            return self._value < other._value
        else:
            return NotImplemented

    def __le__(self, other):
        if isinstance(other, ByteSize):
            return self._value <= other._value
        else:
            return NotImplemented

    def __add__(self, other):
        if isinstance(other, ByteSize):
            return ByteSize(self._value + other._value)
        else:
            return NotImplemented

    def __iadd__(self, other):
        if isinstance(other, ByteSize):
            self._value += other._value
            return self
        else:
            return NotImplemented

    def __sub__(self, other):
        if isinstance(other, ByteSize):
            return ByteSize(self._value - other._value)
        else:
            return NotImplemented

    def __isub__(self, other):
        if isinstance(other, ByteSize):
            self._value -= other._value
            return self
        else:
            return NotImplemented

    def __mul__(self, other):
        if isinstance(other, integer_types):
            return ByteSize(self._value * other)
        else:
            return NotImplemented

    def __imul__(self, other):
        if isinstance(other, integer_types):
            self._value *= other
            return self
        else:
            return NotImplemented

    def __floordiv__(self, other):
        if isinstance(other, integer_types):
            return ByteSize(self._value//other)
        else:
            return NotImplemented

    def __str__(self):
        if self._value < 0:
            return '-{}'.format(format_size(-self._value, binary=True))
        else:
            return format_size(self._value, binary=True)

    def __repr__(self):
        return 'ByteSize({})'.format(self._value)

    def __neg__(self):
        return ByteSize(-self._value)

    def get_bytes(self):
        return self._value

    def get_gigabytes(self):
        return self._value / (1024 * 1024 * 1024)
