#!/usr/bin/python
# -*- coding:utf-8 -*-

# Author: Pablo Saavedra Rodinho
# Contact: pablo.saavedra@treitos.com

# Author: Pablo Abelenda Gonzalez
# Contact: pablo.abelenda@gmail.com

"""
Generate an html mosaic from a collection of dump files

"""

from optparse import OptionParser

import os
import sys
import subprocess

reload(sys)
sys.setdefaultencoding('utf-8')

import ConfigParser
import simplejson as json


import time
from datetime import datetime
import struct
import socket

import urllib2
import httplib2

DEV_NULL=open('/dev/null', "w")

conffile = "./checker.cfg"

logfile = "/dev/stdout"
loglevel = 20
workdir = "./checker/"


# command line options parser ##################################################

parser = OptionParser()

parser.add_option("-f", "--file", dest="conffile",
        help="The configuration file (default: %s)" % conffile,
        default=conffile)
parser.add_option("-w", "--workdir", dest="workdir", default=workdir,
        help="Work directory (default: %s)" % workdir)
parser.add_option("-l", "--logfile",
        dest="logfile", help="Log file (default: %s)" % logfile,
        default=logfile)
parser.add_option("--loglevel",
        dest="loglevel", help="Log level (default: %s)" % loglevel,
        default=loglevel)
(options, args) = parser.parse_args()

conffile = options.conffile

workdir = options.workdir
logfile = options.logfile
loglevel = options.loglevel


# logging ######################################################################
import logging
hdlr = logging.FileHandler(logfile)
hdlr.setFormatter(logging.Formatter('%(levelname)s %(asctime)s %(message)s'))
logger = logging.getLogger('fluunt')
logger.addHandler(hdlr)
logger.setLevel(int(loglevel))


# setting up ###################################################################

logger.info("Default encoding: %s" % sys.getdefaultencoding())

if not os.path.isfile(workdir):
    try:
        os.mkdir(workdir)
    except OSError, e:
        m = str(e)
        logger.warning(m)

prefix = workdir + "/dumps/"
if not os.path.isfile(prefix):
    try:
        os.mkdir(prefix)
    except OSError, e:
        m = str(e)
        logger.warning(m)

frames_dir = workdir + "/frames/"
if not os.path.isfile(frames_dir):
    try:
        os.mkdir(frames_dir)
    except OSError, e:
        m = str(e)
        logger.warning(m)

################################################################################


def main():
    global conffile
    '''
['key_http']
uri="http://localhost:8082"
protocol="http"
chunkduration=30

['key_udp']
ip="127.0.0.1"
port=1234
protocol="udp"
chunkduration=30

    '''
    dbfilename = workdir + '/checks.db'
    dbfilename_tmp = workdir + '/checks.db.tmp'

    try:
        dbfile = open(dbfilename)
        db_json = json.load(dbfile)
        dbfile.close()
    except Exception:
        db_json = None

    res = {}

    try:
      # RawConfigParser not interpolate attribute values
      cfg = ConfigParser.RawConfigParser()
      cfg.readfp(file(conffile))

    except Exception, e:
        print ("Conffile %s error: %s" % (conffile,e))

    for s in cfg.sections():
        key = s
        try:
          uri = None
          ip = None
          port = None
          chunkduration = 10
          protocol = None
          threshold = 1
          mosaic = False
          if s == 'global':
              for o in cfg.options(s):
                  try:
                      vars()[o] = cfg.get(s,o)
                  except Exception, e:
                      print "Error parsing %s - %s: %s" % (s,o,e)
              continue

          for o in cfg.options(s):
              uri = eval (cfg.get(s,o)) if o == 'uri' else uri
              ip = eval (cfg.get(s,o)) if o == 'ip' else ip
              port = eval (cfg.get(s,o)) if o == 'port' else port
              chunkduration = eval (cfg.get(s,o)) if o == 'chunkduration' else chunkduration
              protocol = eval (cfg.get(s,o)) if o == 'protocol' else protocol
              threshold = eval (cfg.get(s,o)) if o == 'threshold' else threshold
              mosaic = eval (cfg.get(s,o)) if o == 'mosaic' else mosaic

          if mosaic == True:
              logger.info ("Checking %s stream [protocol=%s uri=%s ip=%s port=%s chunkduration=%s threshold=%s]" \
              % (key,protocol, uri, ip,port,chunkduration,threshold))
              do_frames(key)

        except IOError, e:
          logger.error ("Problem on %s stream: %s" % (key,e))

    do_html()



def do_frames(key):
    dumpfilename = str(workdir) + '/dumps/' + str(key) + ".dump"
    frame_dir = frames_dir + key
    if not os.path.isfile(frame_dir):
        try:
            os.makedirs(frame_dir)
        except OSError, e:
            m = str(e)
            logger.warning(m)

    cmd="ffmpeg -loglevel quiet -i " + dumpfilename + " -r 1 " + frame_dir + "/img%1d.jpg  >/dev/null 2>&1"
    logger.debug("Command to execute: %s" % cmd)
    os.popen(cmd)


def do_html():
    html_file = workdir + "/index.html"
    html_output = open (html_file, "w" )

    begin_header = "<html>\n<head>\n<meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\">\n"
    title ="<h3>Channel mosaic</h3>"
    style1="<style type=\"text/css\">div#mosaic {}"
    style2="div.element { float:left; height: 115px; margin:0; padding:0; width:150px; }"
    style3="div.element span.title {color:#000; font-size:10px; align:center; }"
    style4="div.element img { height:100px; width:150px; } </style>"
    end_header="</head>"
    begin_body="<body> <div id=\"mosaic\">"
    footer = "</div> </body> </html>"

    html_output.write(begin_header)
    html_output.write(title)
    html_output.write(style1)
    html_output.write(style2)
    html_output.write(style3)
    html_output.write(style4)
    html_output.write(end_header)
    html_output.write(begin_body)

    frames_dir = workdir + "/frames/"
    for i in os.listdir(frames_dir):
        l_frames = os.listdir(frames_dir + "/" + i)
        l_frames.sort()
        if l_frames == []:
            abs_filename = "no_image_found"
            image_code="<div class=\"element\"> <span class=\"title\"> %s </span> <img src=%s alt=Channel %s title=%s width=\"150\" height=\"100\" > </div>  \n" %(i, abs_filename,i,i)
            html_output.write(image_code)
        else:
            filename=l_frames[len(l_frames)-1]
            # abs_filename = os.path.abspath(frames_dir + "/" + i + "/" + filename)
            abs_filename = "frames/" + i + "/" + filename
            image_code="<div class=\"element\"> <span class=\"title\"> %s </span> <img src=%s alt=Channel %s title=%s width=\"150\" height=\"100\" > </div>  \n" %(i, abs_filename,i,i)
            html_output.write(image_code)

    html_output.write(footer)
    html_output.close()


# main #########################################################################

if __name__ == '__main__':
    main()
