# -*- coding: utf-8 -*-
'''
Created on Mar 22, 2013

@author: tc
'''

from datetime import datetime
from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand, CommandError
from ldt.api.ldt.serializers.cinelabserializer import CinelabSerializer
from ldt.ldt_utils.models import Media, Content, Project
from ldt.ldt_utils.projectserializer import ProjectJsonSerializer
from ldt.ldt_utils.stat import update_stat_content
from ldt.security import set_current_user
#from string import replace
import copy
import csv
import json
import lxml.etree
#import os.path
#import requests
#import time

import logging
logger = logging.getLogger(__name__)

User = get_user_model()

class Command(BaseCommand):
    '''
    Load medias, contents, project from json generated by ubicast
    '''

    args = 'csv data file'
    help = 'generates json files for demonstrateur contents and project'
    
    
    def __safe_get(self, dict_arg, key, conv = lambda x: x, default= None):
        val = dict_arg.get(key, default)
        return conv(val) if val else default

    def __safe_decode(self, s):
        if not isinstance(s, basestring):
            return s
        try:
            return s.decode('utf8')
        except:
            try:
                return s.decode('latin1')
            except:
                return s.decode('utf8','replace')
    
    def apply_exceptions(self, a):
        if a["id"]=="a17" and a["media"]=="travail-sur-lacte-1-jour-15_b822f8":
            a["end"] = 2723000
        elif a["id"]=="a86" and a["media"]=="travail-sur-lacte-3-et-lacte-1-jour-22_4c3a75":
            a["begin"] = 20925000
            a["end"] = 21290000
        elif a["id"]=="a1" and a["media"]=="premier-bout-a-bout-de-la-piece-jour-23_73654f":
            a["end"] = 728000
        elif a["id"]=="a1" and a["media"]=="bout-a-bout-avec-les-enfants_a4c293_SON_SATURE":
            a["end"] = 560000
        elif a["id"]=="a1" and a["media"]=="filage-technique-jour-40-deuxieme-partie_58b2a6_SON_GRESILLE":    
            a["end"] = 560000
        elif a["id"]=="a105" and a["media"]=="travail-sur-lacte-2-jour-18_5e9fe9":
            a["begin"] = 19628000
        elif a["id"]=="a117" and a["media"]=="travail-sur-lacte-2-jour-18_5e9fe9":
            a["end"] = 22080000
        

    def handle(self, *args, **options):
        
        # Test path
        if len(args) != 1:
            raise CommandError("The command has no argument or too much arguments. Only one is needed : the csv file.")
        
        with open(args[0], 'rU') as datafile:
            reader = csv.reader(datafile)
            lines = list(reader)
            last_content_id = ""
            count_content = 0
            
            admin = User.objects.filter(is_superuser=True)[0]
            set_current_user(admin)
            
            for line in lines:
                # Test content id and main annotation id
                if line[0]!="":
                    content_title = unicode(line[1].decode('utf-8'))
                    prefix = "[demo] "
                    tag = "demo"
                    if line[0]=="Duo Brick et Maggy en introduction\n[7-1 à 9-5]":
                        tag = "demo1"
                    elif line[0]=="51-13 à 56.15":
                        tag = "demo2"
                    prefix = "[" + tag + "] "
                content_id = line[1]
                pre_annot_id = line[2]
                pre_annot_tcin_hms = line[3]
                pre_annot_tcin_ms = line[4]
                pre_annot_tcout_hms = line[5]
                pre_annot_tcout_ms = line[6]
                annot_id = line[7]
                annot_tcin_hms = line[10]
                annot_tcin_ms = line[11]
                annot_tcout_hms = line[12]
                annot_tcout_ms = line[13]
                post_annot_id = line[14]
                post_annot_tcin_hms = line[15]
                post_annot_tcin_ms = line[16]
                post_annot_tcout_hms = line[17]
                post_annot_tcout_ms = line[18]
                created_ctt_id = line[19]
                try:
                    created_tcin_ms = int(line[21])
                except:
                    created_tcin_ms = False
                try:
                    created_tcout_ms = int(line[24])
                except:
                    created_tcout_ms = False
                try:
                    created_ctt_dur = int(line[25])
                except:
                    created_ctt_dur = False
                if content_id != "" and created_ctt_id != "" and created_tcin_ms and created_tcout_ms and created_ctt_dur:
                    if last_content_id != content_id:
                        last_content_id = content_id
                        count_content = 0
                        print "get content iri_id = " + last_content_id
                        ctt_source = Content.objects.filter(iri_id = last_content_id).select_related("front_project")[0]
                        ps = ProjectJsonSerializer(ctt_source.front_project)
                        print "project ldt_id = " + ctt_source.front_project.ldt_id
                        project_source_data = ps.serialize_to_cinelab()
                    
                    if annot_id != "" and project_source_data:
                        count_content += 1
                        # Get tc from annotations datas
                        tc_offset = annot_tcin_ms
                        #tc_end = annot_tcout_ms
                        if pre_annot_id != "":
                            tc_offset = pre_annot_tcin_ms
                        tc_offset = int(tc_offset)
                        #if post_annot_id != "":
                        #    tc_end = post_annot_tcout_ms
                        
                        # data to create new data
                        ctt_title = prefix + content_title + u" : extrait " + (u"0" if count_content<10 else u"") + unicode(count_content)
                        media_src = "/data/demonstrateur/"+content_id+"/" + created_ctt_id + ".mp4"
                        if hasattr(settings, "DEMONSTRATEUR_DOMAIN") and len(settings.DEMONSTRATEUR_DOMAIN)>0:
                            media_src = settings.DEMONSTRATEUR_DOMAIN + media_src
                        media, _ = Media.objects.get_or_create(src=media_src, duration=created_ctt_dur)
                        media.is_public = True
                        content, _ = Content.objects.get_or_create(iri_id = created_ctt_id, 
                                                                 iriurl = created_ctt_id+u"/"+created_ctt_id+u".iri", 
                                                                 media_obj = media, 
                                                                 title = ctt_title, 
                                                                 duration = created_ctt_dur)
                        content.is_public = True
                        update_stat_content(content)
                        content.tags.add(tag + "_theatre")
                        # Get content front projet
                        proj = content.front_project
                        ps = ProjectJsonSerializer(proj)
                        proj_data = ps.serialize_to_cinelab()
                        proj_data["annotations"] = []
                        for a in project_source_data["annotations"]:
                            #print "get content 12"
                            if (a["id"] in [pre_annot_id, annot_id, post_annot_id] and a["meta"]["id-ref"]!="interpretation") or (a["meta"]["id-ref"]=="interpretation" and created_tcin_ms<=a["begin"] and a["begin"]<=created_tcout_ms):
                                #if a["meta"]["id-ref"]=="interpretation":
                                #    print "AJOUT interpretation " + a["id"]
                                if a["meta"]["id-ref"]!="interpretation":
                                    self.apply_exceptions(a)
                                temp_a = copy.deepcopy(a)
                                b = temp_a["begin"]
                                temp_a["begin"] = temp_a["begin"] - created_tcin_ms
                                temp_a["end"] = temp_a["end"] - created_tcin_ms
                                if a["meta"]["id-ref"]=="interpretation":
                                    temp_a["end"] = min(temp_a["end"], created_ctt_dur)
                                temp_a["media"] = created_ctt_id
                                if temp_a["begin"] < 0:
                                    print created_ctt_id + " : " + temp_a["id"] + " : < 0 : serveur : " + str(b) + ", excel : " + str(tc_offset) + ", created_tcin_ms : " + str(created_tcin_ms)
                                if temp_a["end"] > created_ctt_dur:
                                    print created_ctt_id + " : " + temp_a["id"] + " : > " + str(created_ctt_dur) + " : " + str(temp_a["end"])
                                proj_data["annotations"].append(temp_a)
                        # The annotation-types
                        for at in project_source_data["annotation-types"]:
                            #print "get content 15"
                            proj_data["annotation-types"].append(at)
                            proj_data["views"][0]["annotation_types"].append(at["id"])
                            proj_data["lists"][0]["items"].append({ "id-ref": at["id"] })
                        # The tags
                        proj_data["tags"] = project_source_data["tags"]
                        #print json.dumps(proj_data, indent=2)
                        
                        serializr = CinelabSerializer()
                        serializr.validate_cinelab_json(proj_data)
                        ldt_xml = serializr.cinelab_to_ldt(proj_data) 
                        #print lxml.etree.tostring(ldt_xml, pretty_print=True)
                        proj.ldt = lxml.etree.tostring(ldt_xml, pretty_print=True)
                        #logger.debug(proj.ldt)
                        proj.save()
                        update_stat_content(content)
                        
                        #print ctt_title + " : " + created_ctt_id
                    
                else:
                    print "Nope"
        # This is the end
        print("This is the end.")
        