#!/usr/bin/python

"""This is a module to extract rating information from the digikam database. 

Usage: ratingpyramid [FILENAME] 
FILENAME is the full path to a valid digikam database. If not given, 
a default database '~/Images' is used. """

from __future__ import division         # Division must be float or code will be messed up!
import sqlite3       
import Tkinter as tk   #Note the case! Lower case for Python3! (i.e. 'tkinter')
import os.path
import sys

DB_path = sys.argv[1]

def get_ratings(path = os.path.expanduser("~/Images")):
# Get ratings from specified digikam database
    cxn = sqlite3.connect(path)
    cur = cxn.cursor()

    res = []
    for val in range(-1,6):
        cur.execute('''
        SELECT count(*)
        FROM images JOIN imageinformation
        ON(images.id=imageinformation.imageid)
        WHERE images.album IS NOT NULL AND imageinformation.rating = %s
        ''' % val)
        res.append(cur.fetchone()[0])

    cxn.close()
    return res

def tk_visualise(v = [34,243,81,27,9,3],r = range(-1,6)):
    X, Y = 600, 400
    d = 0.1
    N = len(v)
    root = tk.Tk()
    root.title('Rating Pyramid')
    f1 = tk.Frame(root, width=X, height=Y)
    f1.pack(anchor="c", fill="both", expand=True, padx=20, pady=20)
    canvas = tk.Canvas(f1, width=X, height=Y, bg='white') #% (X, Y)
    xy = []
    # Create the coordinates to plot in the xy-vector
    for i in range(0,N):
        xy.append((X * (1 + (v[i]/max(v)) ) / 2, Y * (1 - i/(N-1))))
        if i == 0:
            canvas.create_text(X/2 ,Y * (1 - i/(N-1)),text=v[i],anchor=tk.S)
            canvas.create_text(0.025*X, Y * (1 - i/(N-1)),text=r[i],anchor=tk.S)
        elif i == N-1:
            canvas.create_text(X/2 ,Y * (1 - i/(N-1)),text=v[i],anchor=tk.N)
            canvas.create_text(0.025*X, Y * (1 - i/(N-1)),text=r[i],anchor=tk.N)
        else:
            canvas.create_text(X/2 ,Y * (1 - i/(N-1)),text=v[i],anchor=tk.CENTER)
            canvas.create_text(0.025*X, Y * (1 - i/(N-1)),text=r[i],anchor=tk.CENTER)
    # This is the other side of the vector
    for i in range(N-1,-1,-1):
        xy.append((X * (1 - (v[i]/max(v)) ) / 2, Y * (1 - i/(N-1))))
    # Plot the rating pyramid
    canvas.create_polygon(xy,fill='',outline='black',smooth=0)
    
    canvas.pack()

if __name__ == '__main__':
    global DB_path
    res = get_ratings(DB_path)
    # Plot all ratings
    tk_visualise(res,range(-1,6))
    print(res)
    # Plot only ratigs 1-5
    tk_visualise(res[2:len(res)],range(1,6))
    raw_input("Press any key to exit")
    print('Exiting...')
