#!/usr/bin/env python
# vim: set fileencoding=UTF-8 :

# Copyright (c) 2010, Jonas Häggqvist <rasher@rasher.dk>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
#   list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
#   this list of conditions and the following disclaimer in the documentation
#   and/or other materials provided with the distribution.
# * Neither the name of the program nor the names of its contributors may be
#   used to endorse or promote products derived from this software without
#   specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.

# How to use:
# 1. Grab a copy of IMDb's ratings dump: http://www.imdb.com/interfaces#plain
# 2. And a ttf font (I use dejavusans.ttf, you'll have to adjust the filename
#    below if you want to use something else)
# 3. Modify movies.txt to suit
# 4. Run - enjoy! (hopefully)
# 5. ???
# 6. Profit! - tell me if you reach this far

import re
import sys
import codecs
import os.path
from pprint import pprint
import Image, ImageDraw, ImageFont
from math import sqrt, pow

def draw(name, values, colors=None, maxvalue=None, minvalue=None):
    topmargin = 16
    barwidth = 33
    barheight = 44
    linewidth = 2
    linecolor = '#000000'
    bgcolor = '#FFFFFF'
    barcolor = '#008ECC'
    fontsize = 15
    barcolors = [
            '#086FA1',
            '#8F04A8',
            '#DCF900',
            '#FF9800',
            '#034769',
            '#5D016D',
            '#8fA200',
            '#A65900',
    ]

#    barcolors = [
#        '#008ECC',
#        '#CCBE66',
#        '#CC0070',
#        '#CCB000',
#        '#CC669E',
#        '#8E00CC',
#    ]

    if maxvalue == None:
        maxvalue = max(values)
    if minvalue == None:
        minvalue = min(values)
    percentages = []
    for value in values:
        percentages.append((value-minvalue)/float((maxvalue-minvalue)))

    width = (linewidth+barwidth)*len(percentages)+linewidth
    height = barheight+2*linewidth+topmargin

    im = Image.new("RGBA", (width, height), bgcolor)
    draw = ImageDraw.Draw(im)

    titlewidth = width+1
    titleheight = topmargin+1
    while titlewidth > width or titleheight > topmargin:
        font = ImageFont.truetype('dejavusans.ttf', fontsize)
        titlewidth, titleheight = draw.textsize(name, font=font)
        fontsize -= 1
    draw.text(((width-titlewidth)/2,0), name, font=font, fill=linecolor)

    draw.rectangle([(0, topmargin), (width,height)], fill=linecolor)
    for i in range(len(percentages)):
        x1, y1 = ((linewidth+barwidth)*i+linewidth, topmargin+linewidth)
        x2, y2 = (x1+barwidth-1, y1+barheight-1)
        draw.rectangle([(x1,y1), (x2,y2)], fill=bgcolor)
        y1 = int(y2 - percentages[i]*barheight + 1)
        if y1 <= y2:
            draw.rectangle([(x1,y1), (x2,y2)], fill=barcolors[colors[i]])
    return im

def gatherdata():
    allmovies = {}
    alltitles = {}
    curseries = ""

    movies = codecs.open('movies.txt', 'r', 'utf8')
    for line in movies.readlines():
        if len(line.strip()) == 0 or line[0] == "#":
            continue
        elif line[0] == " ":
            if line[1] in ['0','1','2','3','4','5']:
                color = int(line[1])
                title = line[2:].strip()
            else:
                color = 0
                title = line.strip()
            allmovies[curseries].append([title, None, color])
            alltitles[title] = None
        else:
            curseries = line.strip()
            allmovies[curseries] = []
    movies.close()

    ratings = codecs.open('ratings.list', 'r', 'cp1252')
    r = re.compile('^      .......... .......  (?P<rating>....)  (?P<title>.*? \([12][890][0-9][0-9](/[IV]+)?\).*)$')
    for line in ratings.readlines():
        m = r.match(line)
        if m and m.group('title') in alltitles:
            alltitles[m.group('title')] = float(m.group('rating'))
    ratings.close()

    globalmax = 0.0
    globalmin = 10.0
    for series, movies in allmovies.iteritems():
        if len(movies) > 1:
            for movie in movies:
                movie[1] = alltitles[movie[0]]
                if movie[1] == None:
                    print "%s missing" % movie[0]
                    sys.exit()
            globalmax = max(globalmax, max([m[1] for m in movies]))
            globalmin = min(globalmin, min([m[1] for m in movies]))
    pprint(allmovies)
    return allmovies, globalmax, globalmin

def printstats(movies):
    diffs = [
            ("First to sequel", 0, 1),
            ("First to third", 0, 2),
            ("Sequel to third", 1, 2),
            ]
    for text, fromnumber, tonumber in diffs:
        mean = sum([s[tonumber][1] - s[fromnumber][1] for s in movies.values()])/len(movies.values())
        stddev = sqrt(sum([pow(s[tonumber][1] - s[fromnumber][1] - mean, 2) for s in movies.values()])/len(movies.values()))
        print "%s: Mean=%0.2f StdDev=%0.2f" % (text, mean, stddev)

if __name__ == "__main__":
    allmovies, globalmax, globalmin = gatherdata()
    for series, movies in allmovies.iteritems():
        if len(movies) < 1:
            continue
        ratings = [m[1] for m in movies]
        colors = [m[2] for m in movies]
        
        im = draw(series, ratings, colors, maxvalue=10, minvalue=1)
        im.save('absolute/%s.png' % series)
        im = draw(series, ratings, colors)
        im.save('relative/%s.png' % series)
        im = draw(series, ratings, colors, maxvalue=globalmax, minvalue=globalmin)
        im.save('globalrelative/%s.png' % series)
    printstats(allmovies)

