import logging

from pylons import request, response, session, tmpl_context as c, url
from pylons.controllers.util import abort, redirect

from ppdi.lib.base import BaseController, render

from ppdi.model.meta import Session
from ppdi.model import Conference, ConferenceAction, ModeratorPin

from time import strptime
from datetime import datetime

from ppdi.lib import helpers as h

import os

from sqlalchemy import and_
from sqlalchemy.orm.exc import NoResultFound

log = logging.getLogger(__name__)

class ReportsController(BaseController):

    requires_auth = True

    def index(self):
        c.confs = Session.query(ModeratorPin).filter(ModeratorPin.username == session.get('username')).all()
        oConfs = Session.query(ModeratorPin).filter(ModeratorPin.extraAdmin == session.get('username')).all()
        
        c.oConfs = {}
        for conf in oConfs:
            if c.oConfs.has_key(conf.username):
                c.oConfs[conf.username].append(conf)
            else:
                c.oConfs[conf.username] = [conf,]
        return render('/derived/main/reports_select.html')
        
    def gen_report(self):
        """View the reports"""
        conf_name = request.params.get('conf_name')
        date_from = request.params.get('date_from')
        date_to = request.params.get('date_to')
        stmt = Session.query(Conference).join(ModeratorPin).filter(ModeratorPin.username == session.get('username'))

        if date_from and date_to:
            try:
                ddate_from = datetime(*strptime(date_from, '%m/%d/%Y')[:3])
                ds = strptime(date_to, '%m/%d/%Y')
                ddate_to = datetime(ds[0], ds[1], ds[2] , 23, 59, 59)
                stmt = stmt.filter(and_(Conference.created >= ddate_from, Conference.ended <= ddate_to))
            except ValueError, e:
                log.warning('User has supplied the wrong time format, disregarding filter: %s %s' % (date_from, date_to))
                h.flash('Invalid date format.')
                redirect(url(controller='main/reports', action='index'))
                
                
        if conf_name:
            stmt = stmt.filter(Conference.name == conf_name)
            
        try:
            c.confs = stmt.all()
        except Exception, e:
            print e
        return render('/derived/main/reports_gen.html')
        
    def report_detail(self, id):
        """Generate a detailed report from the conference"""
        try:
            c.conf = Session.query(Conference).join(ModeratorPin).filter(Conference.id == id).one()
        except NoResultFound, e:
            log.critical(e)
            
        self.is_my_pin(c.conf.owner)
        c.actions = Session.query(ConferenceAction).join(Conference).filter(Conference.id == id).all()
        return render('/derived/main/reports_detail.html')

    def dl_recording(self, id):
        """Download the recording for a conference"""
        try:
            conf = Session.query(Conference).join(ModeratorPin).filter(and_(ModeratorPin.username == session.get('username'), Conference.id == id)).one()
        except NoResultFound, e:
            return 'No such conference.'
            
        if not os.path.exists(conf.recording):
            return 'No recording available for this conference.'

        return self._send_file_response(conf.recording)
        
    def _send_file_response(self, filepath):
        user_filename = filepath.split('/').pop()
        file_size = os.path.getsize(filepath)

        headers = [('Content-Disposition', 'attachment; filename=\"' + user_filename + '\"'),
                   ('Content-Type', 'audio/mpeg'),
                   ('Content-Length', str(file_size))]

        from paste.fileapp import FileApp
        fapp = FileApp(filepath, headers=headers)

        return fapp(request.environ, self.start_response)
