# -*- coding: utf-8 -*-
#
# prettysize - print data sizes in format easily readable by humans
#
# Copyright (c) 2011  Radek Brich <radek.brich@devl.cz>
#
# 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.

iec_prefixes = ('Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi', 'Yi')
si_prefixes = 'kMGTPEZY'
big_prefixes = 'KMGTPEZY'


def prettysize(num, base=1024, prefixes=si_prefixes, unit='B', sep=' '):
    '''Convert data size in bytes to human readable aproximation.

    Beware that default output is invalid by recent standardization.
    Still, this form was in use for ages.

    For standardized output, see prettysize_si and prettysize_iec.

    '''
    prefixes = list(prefixes)
    prefix = ''
    num = float(num)
    while True:
        if num < base:
            # format number
            out = '{:.2f}'.format(num)
            # cut off trailing zeros
            out = out.rstrip('0')
            if out.endswith('.'):
                out = out[:-1]
            return out + sep + prefix + unit
        num /= base
        prefix = prefixes.pop(0)

    raise OverflowError('Number is too large.')


def prettysize_si(num, **kw):
    return prettysize(num, base=1000, **kw)


def prettysize_short(num):
    return prettysize(num, unit='', sep='', prefixes=big_prefixes)


def prettysize_iec(num):
    return prettysize(num, prefixes=iec_prefixes)

