# -*- coding: utf8 -*-
from pyramid.response import Response
import cStringIO as StringIO
from pyramid.view import view_config
from .models import DBSession, Event, Salles
from reportlab.pdfgen import canvas
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.lib.units import mm
from .upload import MediaPath
from jm2l.const import CurrentYear

# Create PDF container
EXPIRATION_TIME = 300 # seconds
WIDTH = 210 * mm
HEIGHT = 297 * mm
ICONSIZE = 10 * mm


def JM2L_large_Logo(canvas, Offset=(0,0)):
    OffX, OffY = Offset
    
    canvas.setFont('Logo', 110)
    canvas.setFillColorRGB(.83,0,.33)
    canvas.drawCentredString(WIDTH/2-OffY, HEIGHT-100-OffX, "JM2L")

    canvas.setFont("Helvetica-Bold", 30)
    yearobject = canvas.beginText()
    yearobject.setFillColorRGB(1,1,1)
    yearobject.setTextRenderMode(0)
    yearobject.setTextOrigin(WIDTH/2-OffY-120, HEIGHT-36-OffX)
    yearobject.setWordSpace(48)
    yearobject.textLines("2 0 1 5")
    yearobject.setWordSpace(1)    
    canvas.drawText(yearobject)  

def one_time_step(canvas, str, hour, max_size, offset):
    max_x, max_y = max_size
    off_x, off_y = offset
    step_y = max_y/9
    half_step = step_y/2
    canvas.drawCentredString(off_x-30, max_y-step_y*hour+off_y-3, str)
    hour_place = step_y*hour+off_y
    canvas.line(off_x-5, hour_place, off_x, hour_place)
    if hour<9:
        canvas.line(off_x-2, hour_place+half_step, off_x, hour_place+half_step)


@view_config(route_name='stand_print', http_cache = (EXPIRATION_TIME, {'public':True}))
def stand_print(request):
    # Ok let's generate a print for place schedule
    
    # Register LiberationMono font
    ttfFile = "jm2l/static/fonts/LiberationMono-Regular.ttf"
    pdfmetrics.registerFont(TTFont("Liberation", ttfFile))
    # Import font
    ttfFile_Logo = "jm2l/static/fonts/PWTinselLetters.ttf"
    pdfmetrics.registerFont(TTFont("Logo", ttfFile_Logo))

    pdf = StringIO.StringIO()
  
    c = canvas.Canvas( pdf, pagesize=(HEIGHT, WIDTH) )
    c.translate(mm, mm)
    
    # Feed some metadata
    c.setCreator("linux-azur.org")
    c.setTitle("Affiches stand")

    c.saveState()
    
    year = int(request.matchdict.get('year', CurrentYear))

    Events = DBSession.query(Event)\
        .filter(Event.for_year == year)\
        .filter(Event.event_type == "Stand")

    for ev in Events:
        c.setFont('Logo', 50)
        c.setFillColorRGB(.5,.5,.5)
        c.drawString(HEIGHT-150, 30, "JM2L")
        c.setFont('Logo', 100)
        c.setFillColorRGB(0.5,0.5,0.5)
        c.drawCentredString(HEIGHT/2, WIDTH-90, "STAND", 0)        
        c.setFillColorRGB(0,0,0)
        c.setFont('Helvetica', 42)
        c.drawCentredString(HEIGHT/2, WIDTH/2, ev.name, 0)        
        c.showPage()

    c.save()
    pdf.seek(0)

    return Response(app_iter=pdf, content_type = 'application/pdf' )



@view_config(route_name='place_print', http_cache = (EXPIRATION_TIME, {'public':True}))
def place_print(request):
    # Ok let's generate a print for place schedule
    
    # Register LiberationMono font
    ttfFile = "jm2l/static/fonts/LiberationMono-Regular.ttf"
    pdfmetrics.registerFont(TTFont("Liberation", ttfFile))
    # Import font
    ttfFile_Logo = "jm2l/static/fonts/PWTinselLetters.ttf"
    pdfmetrics.registerFont(TTFont("Logo", ttfFile_Logo))

    pdf = StringIO.StringIO()
  
    c = canvas.Canvas( pdf, pagesize=(WIDTH, HEIGHT) )
    c.translate(mm, mm)
    
    # Feed some metadata
    c.setCreator("linux-azur.org")
    c.setTitle("Planning Salle")

    c.saveState()
    
    year = int(request.matchdict.get('year', CurrentYear))
    # Initialization
    # Compute days used by all events matching the specified input year
    place_used = DBSession.query(Event.salle_uid)\
                .filter(Event.for_year == year)\
                .filter(Event.event_type != 'Stand')\
                .group_by(Event.salle_uid)
   
    for place in place_used:
        place_uid = place[0] 
        place_obj = Salles.by_id(place_uid)
        # Logo on Top
        JM2L_large_Logo(c)
        max_size = (WIDTH-110, HEIGHT-300)
        offset = (70, 90)
        c.setFillColorRGB(.5,.5,.5)
        c.setFont('Liberation', 40)
        c.drawCentredString(WIDTH/2, HEIGHT-190, place_obj.name, 1)
        c.setFont('Liberation', 35)
        c.drawCentredString(WIDTH/2, HEIGHT-145, place_obj.place_type, 0 )
        c.setFont('Helvetica', 20)        
        c.drawCentredString(WIDTH/2, 55, place_obj.phy.name, 0)        
        
        # Timetable container
        c.setLineWidth(.1)
        c.setLineCap(2)
        #c.setFillColorRGB(0,0,1)        
        c.rect(offset[0], offset[1], max_size[0], max_size[1], fill=0, stroke=1)
        c.setLineWidth(.5)        
        # create time mark
        c.setFillColorRGB(0,0,0)
        c.setFont('Helvetica', 10)
        for i in range(0,10):
            one_time_step(c, "%.2dh00" % (i+10), i, max_size, offset)

        #c.setFont('Helvetica', 12)
        Events = DBSession.query(Event)\
            .filter(Event.for_year == year)\
            .filter(Event.salle_uid == place_uid)\
            .order_by(Event.start_time)       
        for ev in Events:
            place_time(c, ev, max_size, offset)
            #c.rect(70, 50, WIDTH-100, HEIGHT-250, fill=0, stroke=1)
        c.showPage()

    c.save()
    pdf.seek(0)

    return Response(app_iter=pdf, content_type = 'application/pdf' )

def place_time(c, ev, max_size, offset):
    max_x, max_y = max_size
    off_x, off_y = offset
    minute = max_y/(9*60)
    start_pos_y = ((int( ev.start_time.strftime('%H') )-10)*60 + int( ev.start_time.strftime('%M') )) * minute
    stop_pos_y = ((int( ev.end_time.strftime('%H') )-10)*60 + int( ev.end_time.strftime('%M') )) * minute

    c.setFillColorRGB(0.98,0.98,0.98)
    c.rect(offset[0], max_y + off_y - start_pos_y, max_size[0], start_pos_y-stop_pos_y, fill=1, stroke=1)
    c.setFillColorRGB(0,0,0)
    #c.drawString(off_x+5, max_y + off_y - 15 - start_pos_y, ev.start_time.strftime('%H:%M'), 0)
    c.setFont('Helvetica', 12)    
    c.drawCentredString(WIDTH/2, max_y + off_y - 35 - start_pos_y, ev.name, 0)
    intervs = ', '.join( [x.slug for x in ev.intervenants] )
    c.setFont('Helvetica', 10)    
    c.drawCentredString(WIDTH/2, max_y + off_y - 55 - start_pos_y, intervs, 0)        
    