import os
import models
import time
import json
import config

import datetime
import shutil
import sys
from util import *


def run():
    #sleep so everything else can get started
    time.sleep(10)
    #ppid = os.getppid()
    while True:
        item = models.get_next_queue()
        if item:
            print item
            #item.options = json.loads(item.options)
            #print item.options
            if not item.description:
                print "Getting meta"
                args = " --get-title --get-description --get-duration " + item.origurl
                out,err = runcmd(config.YTDL_BIN+args)
                print out
                title,description,length = out.split("\n")[:3]
                datest = datetime.datetime.now().isoformat(' ')
                models.add_meta(item.id, title,description,length,datest,models.BUSY)
                #models.got_meta(item.id)
                #models.video_busy(id)
            if not item.thumb:
                print "Getting thumb"
                args = " --write-thumbnail --output 'static/thumbs/%(id)s.%(ext)s' --skip-download " + item.origurl
                out,err = runcmd(config.YTDL_BIN+args)
                print out
                print err
                
                models.add_thumb(item.id, item.origid+".jpg")
                #models.got_thumb(item.id)    
                
                
            if not item.video:
                print "Getting video"
                args = " -f mp4 --output 'static/video/%(id)s.%(ext)s' " + item.origurl
                out,err = runcmd(config.YTDL_BIN+args)
                print out
                models.add_video(item.id, item.origid+".mp4")
                #models.got_video(item.id)
                #v = models.get_video_ytid(item.options['ytid'])
                #models.video_done(v.id)
                v = models.get_video(item.id)
                if config.CPDIR:
                    #v = models.get_video_ytid(item.options['ytid'])
                    newfilename = v.title+"-"+v.origid+".mp4"
                    shutil.copy2(os.path.join("./static/video/",v.video), os.path.join(config.CPDIR, newfilename))
                     
                

        else:
            try:
                time.sleep(5)
            except KeyboardInterrupt:
                sys.exit(0)




