#!/usr/bin/python
# -*- Mode: Python -*-
# vi:si:et:sw=4:sts=4:ts=4
#
# Copyright (C) 2005 Michele Baldessari <michele@xsec.it>. All rights reserved.

# This file may be distributed and/or modified under the terms of
# the GNU General Public License version 2 as published by
# the Free Software Foundation.
# This file is distributed without any warranty; without even the implied
# warranty of merchantability or fitness for a particular purpose.
# See "COPYING" in the source distribution for more information.

# Headers in this file shall remain intact.

import getopt, os, csv, sys
import reportlab.pdfgen.canvas
from reportlab.lib import colors
from reportlab.lib.units import mm, cm
from reportlab.lib.pagesizes import A4
from reportlab.pdfbase import pdfmetrics
from math import pi

_TitleTop = ["Biblioteca Comunale", "Trezzo sull'Adda"]
_TitleBottom = ["Donazione De Micheli"]

class LabelSheet38x55:
    # Sheet external margins - Millimeters
    LeftMargin   = 0.3 * cm
    RightMargin  = 0.4 * cm
    TopMargin    = 0.4 * cm
    BottomMargin = 0.5 * cm
    
    HorizMargin  = 0.3 * cm
    VertMargin   = 0.3 * cm
    Width        = 3.8 * cm 
    Height       = 5.5 * cm

    NrCols       = 5
    NrRows       = 5

    SheetHeight  = A4[1]
    SheetWidth   = A4[0]

class Book:
    Inventory      = ""
    Classification = ""
    Id             = ""
    Category       = ""
    

class LabelDialect(csv.excel):
    delimiter = ';'

def usage():
    print "Use: %s <file.csv>"

def grid(c, sheetinfo):
    y = sheetinfo.TopMargin
    x = sheetinfo.LeftMargin
    y1= A4[1] - sheetinfo.BottomMargin
    x1= A4[0] - sheetinfo.RightMargin

    for i in range(0, sheetinfo.NrCols):
        c.line(x, y, x, y1)
        x = x + sheetinfo.Width
        c.line(x, y, x, y1)
        x = x + sheetinfo.HorizMargin
    
    y = sheetinfo.TopMargin
    x = sheetinfo.LeftMargin

    for i in range(0, sheetinfo.NrRows):
        c.line(x, y, x1, y)
        y = y + sheetinfo.Height
        c.line(x, y, x1, y)
        y = y + sheetinfo.VertMargin

def getTextSize(c, text, fontname, fontsize):
    w = c.stringWidth(text, fontname, fontsize)
    face = pdfmetrics.getFont(fontname).face
    ascent = (face.ascent * fontsize) / 1000.0
    descent = (face.descent * fontsize) / 1000.0
    h = ascent - descent 
    return (w, h)

def drawLabel(sheetinfo, c, row, col, book):
    c.setFillGray(0.0)
    x = (sheetinfo.LeftMargin) + (col * (sheetinfo.Width + sheetinfo.HorizMargin))
    y = (sheetinfo.TopMargin) + (row * (sheetinfo.Height + sheetinfo.VertMargin))

    y = sheetinfo.SheetHeight - y - sheetinfo.Height
    print "x, y ", x, y
    c.roundRect(x, y, sheetinfo.Width, sheetinfo.Height , 0.2 * cm)
    
    fontname = 'Helvetica'
    fontsize = 9 
    c.setFont(fontname, fontsize)
    counter = 1 
    for i in _TitleTop:
        (w, h) = getTextSize(c, i, fontname, fontsize)
        leftx = x + ((sheetinfo.Width - w) / 2)
        dytop = y + sheetinfo.Height - ((0.1 * cm) + h) * counter
        c.drawString(leftx, dytop, i)
        counter = counter + 1

    counter = 1
    for i in _TitleBottom:
        (w, h) = getTextSize(c, i, fontname, fontsize)
        leftx = x + ((sheetinfo.Width - w) / 2)
        dy = y + h * counter
        c.drawString(leftx, dy, i)
        counter = counter + 1

    c.saveState()
    (w, h) = getTextSize(c, book.Inventory, fontname, fontsize)
    c.translate(x + sheetinfo.Width, y)
    c.rotate(90)
    print "x, y, book ", x, y, book.Inventory
    c.drawString(0.7 * cm, 0.1 * cm, str(book.Inventory))
    c.restoreState()

    fontsize = 15
    c.setFont(fontname, fontsize)
    Id1 = book.Classification + " " + book.Id[0:3]
    Id2 = book.Id[3:]
    
    dytop = dytop - (1.0 * cm)
    (w, h) = getTextSize(c, Id1, fontname, fontsize)
    leftx = x + ((sheetinfo.Width - w) / 2)
    c.drawString(leftx, dytop - h, Id1)
    
    dytop = dytop - h

    (w, h) = getTextSize(c, Id2, fontname, fontsize)
    leftx = x + ((sheetinfo.Width - w) / 2)
    c.drawString(leftx, dytop - h, Id2)
    
    dytop = dytop - h
    (w, h) = getTextSize(c, book.Category, fontname, fontsize)
    leftx = x + ((sheetinfo.Width - w) / 2)
    c.drawString(leftx, dytop - h, book.Category)


def run(csvreader, filename):
    sheetinfo = LabelSheet38x55()
    print A4

    (shortname, extension) = os.path.splitext(filename)
    c = reportlab.pdfgen.canvas.Canvas(shortname + ".pdf") #FIXME: make this cleaner

    c.translate(mm, mm)
    col = 0 
    row = 0

    for i in csvreader:
        print "call drawlabel row, col ", row, col
        b = Book()
        print i
        b.Inventory = i[0]
        b.Classification = i[1]
        if b.Classification.upper().strip() != "DM":
            b.Classification = ""

        b.Id = i[2]
        b.Category = i[4]

        
        drawLabel(sheetinfo, c, row, col, b)
        col = col + 1 
        if col >= sheetinfo.NrCols:
            col = 0
            row = row + 1
        if row >= sheetinfo.NrRows:
            col = 0
            row = 0
            # Set new page
            c.showPage()

    #grid(c, sheetinfo)
    c.save()
    print c.getAvailableFonts()


def main(args):
    try:
        opts, arguments = getopt.getopt(args, "h:", ["help"])
    except getopt.GetoptError:
        usage()
        sys.exit(2)

            
    for o, a in opts:
        if o in ("-h", "--help"):
            usage()
            sys.exit()

    if (len(arguments) != 1):
        usage()
        sys.exit()

    reader = csv.reader(file(arguments[0]), dialect=LabelDialect)
    run(reader, arguments[0])

if __name__ == '__main__':
    main(sys.argv[1:])
