#!/usr/bin/env python
# -*- coding: utf-8 -*-
# -*- mode: python -*-

"""Call me Ishmael. Dix is a utility for quantifying the size of
plaintext data using a revolutionary metric --- Moby-Dick --- the
number of words in the classic American novel, Moby Dick.
"""

import optparse
import subprocess
import platform
import random
import sys

# colors in terminal
failtext = '\033[91m'

# setup the option parser
parser = optparse.OptionParser(
    usage="%prog [options] [filename] [...]",
    description=__doc__,
)
parser.add_option(
    '-p', '--precision', 
    dest="precision", 
    default=4,
    type="int",
    help="for precision measurement, set the number of decimal places to display"
)
parser.add_option(
    '--tiny', 
    dest="tiny", 
    default=False,
    action="store_true",
    help="use the 'Cozy Classics: Moby Dick' childrens' board book as a basis "\
        +"for comparison, to make yourself feel better",
)
parser.add_option(
    '-u', '--unopinionated', 
    dest="smack", 
    default=True,
    action="store_false",
    help="silence the rude remarks about the size of your data, when you can't"\
        +" handle the heat."
)

opts, filenames = parser.parse_args()

# filenames are specified. read the last line of the output, which
# either displays the total (for multiple files) or the number of
# words (for single file)
if filenames:
    pipe = subprocess.Popen(
        ["wc", "-w"]+filenames, stdout=subprocess.PIPE,
    )
    try:
        last_line = pipe.stdout.read().split('\n')[-2]
    except IndexError:
        sys.stderr.write(failtext + "ERROR: dix unable to count words. \nFile does not exist or unix wc utility not installed. \n\n") 
    big_words = float(last_line.split()[0])

# filename isn't specified, read from stdin instead
else:
    pipe = subprocess.Popen(
        ["wc", "-w"], stdout=subprocess.PIPE, stdin=sys.stdin,
    )
    out, err = pipe.communicate()
    big_words = float(out.strip())

# only print emoji if they have OS X 10.7 (Lion) or above
unit = " Moby-Dicks"
if "Darwin" in platform.platform():
    ver = platform.mac_ver()[0]
    point = ver.split('.')[0:2]

    if int(point[1]) >= 7:
        if opts.tiny:
            unit = u" 🐳"
        else:
            unit = u" 🐋"

if opts.tiny:
    # http://www.amazon.com/Cozy-Classics-Moby-Holman-Wang/dp/1927018110
    base = 12
else:
    base = 209117

# print out the number of moby dicks
# Moby Dick has 209117 words according to Amazon
number_template = u"{0:." + unicode(opts.precision) + u"f}"
print(number_template.format(big_words / base) + unit)

# smack talk 
if opts.smack:
    message = random.choice((
        "Whoa, that's a lot of Moby Dick's!",
        "You call that BIG data?! Please...",
        "Yo' data so big, it probably won't even fit in memory!",
    ))
    print(message.rjust(79))
