# -*- coding: utf-8 -*-
from __future__ import unicode_literals
#!/usr/bin/env python
import sys
import threading
import time
import os, urllib, urllib2, re, subprocess, json
import datetime
import signal
import base64
import psutil
proc = None
workerRtn = False


def makefileW(fpath, data):    
    text_file = open(fpath, "w")
    text_file.write(data)
    text_file.close()
def readfile(fpath):
    data = ''
    text_file = open(fpath, "r")
    data = text_file.read()
    text_file.close()
    return data
def syncData():  
  try:
    eJs = json.loads(readfile(sName+"/epg.json"))["tv"]["programme"]
    ytFiles = ["ffconcat version 1.0"]
    wT= 0
    for prog in eJs:
      st = prog["@start"]
      stT = int(datetime.datetime(int(st[0:4]),int(st[4:6]),int(st[6:8]),int(st[8:10]),int(st[10:12])).strftime('%s'))
      en = prog["@stop"]
      enT = int(datetime.datetime(int(en[0:4]),int(en[4:6]),int(en[6:8]),int(en[8:10]),int(en[10:12])).strftime('%s'))
      cT = time.time()
      if cT> stT and cT< enT:
        fileName = prog["title"]["#text"].replace("file ","")
        fileName = (fileName.encode('ascii', 'ignore')).decode("utf-8")
        cmd = 'ffmpeg -y -i '+fileName+' -ss '+str(cT-stT).split(".")[0]+' -c copy '+sName+'/cut.mp4'
        print cmd
        #cmd =cmd.split()
        proc = subprocess.Popen(cmd,shell=True)
        proc.wait()        
        ytFiles.append("file 'cut.mp4'")
      elif cT<= enT:
        ytFiles.append(prog["title"]["#text"])
      else:
        print "Expired"
    ytFiles.append("file 'list.txt'")    
    makefileW(sName+"/list.txt", ('\n'.join((line.encode('ascii', 'ignore')).decode("utf-8") for line in ytFiles)).replace(sName+"/",""))    
    return wT
  except:
    return 0

def remfiles(f):
    import os
    import glob
    files = glob.glob(f+'/*.ts')
    for fi in files:
        if "tsdata" in fi:
            continue
        try:os.remove(fi)
        except:pass

def kills(pid):
    print "kill called"
    makefileW(sName+"/pidKill", "")
    parent = psutil.Process(int(pid))
    for child in parent.children(recursive=True):
        child.kill()
    parent.kill()
def do_work1(id, stop):
    global proc    
    makefileW(sName+"/strStatus", "ON")    
    while True:
        try:
          makefileW(sName+"/output.m3u8", "")
          remfiles(sName)
          kills(readfile(sName+"/ffpid"))
        except:pass
        if workerRtn:
            return        
        wT = syncData()
        makefileW(sName+"/strMsg", "waiting:"+str(wT))
        time.sleep(wT)
        makefileW(sName+"/strMsg", "Default Url: Stream ONLINE")
        print "starting ffmpeg with Default url with try: " 
        cmd = 'ffmpeg -re -i '+sName+'/list.txt -c copy -f hls -segment_list_type hls -hls_list_size 6 -segment_list_flags +live -hls_flags delete_segments -hls_time 6 '+sName+'/output.m3u8'
        cmd =cmd.split()
        proc = subprocess.Popen(cmd,shell=False)
        print proc.pid
        makefileW(sName+"/ffpid", str(proc.pid))
        proc.wait()        
        makefileW(sName+"/strMsg", "Default Url: Stream OFFLINE")
        time.sleep(10)
        if workerRtn:
            return
                    
        
    
def get_ldata_local(url):
    headers = {'User-Agent': ua[0], 'Connection': 'keep-alive', 'Accept-Encoding': 'gzip, deflate', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'Accept-Language': 'en-US,en;q=0.5'}         
    req = urllib2.Request(url, None, headers)
    response = urllib2.urlopen(req)
    data = response.read()
    response.close()
    return data
    

def clean(*args):
    global workerRtn, iThread
    iThread = "False"
    workerRtn = True
    print "Goodbye!"
    try:
      kills(readfile(sName+"/ffpid"))    
      remfiles(sName)
    except:pass
    makefileW(sName+"/strStatus", "OFF")
    makefileW(sName+"/strMsg", "Stream OFFLINE")
    makefileW(sName+"/output.m3u8", "")
    os._exit(0)


def iWorker2(id):
    while True:
      if iThread == "False":
        break      
      if not os.path.isfile(sName+"/output.m3u8"):
         makefileW(sName+"/output.m3u8", "")
      if time.time() - os.stat(sName+"/output.m3u8").st_mtime > 60:
        try:  
          kills(readfile(sName+"/ffpid"))
          remfiles(sName)
        except:pass 
      else:
        try:makefileW(sName+"/strMsg", "ONLINE:"+str(datetime.timedelta(seconds=time.time() - os.stat(sName+"/ffpid").st_mtime)).split(".")[0])
        except:makefileW(sName+"/strMsg", "ONLINE:")
      print time.strftime("%H:%M")
      if time.strftime("%H:%M") == "04:00":
        try:
          kills(readfile(sName+"/ffpid")) 
          remfiles(sName) 
          time.sleep(70)
        except:pass   
      time.sleep(2)
      

def get_ldata(url, headers = None):
    req = urllib2.Request(url)
    response = urllib2.urlopen(req)
    data = response.read()
    response.close()
    return data
    


iThread = "True"

idT = '0'
sName = sys.argv[0].replace('.py','')
makefileW(sName+"/toggle", "ON")
try:
    pid = readfile(sName+"/pid")
    os.system("kill -9 "+pid)
except:pass
time.sleep(2)
makefileW(sName+"/strStatus","OFF")
makefileW(sName+"/pid",str(os.getpid()))

if readfile(sName+"/strStatus") == "OFF":
    for sig in (signal.SIGABRT, signal.SIGINT, signal.SIGTERM):
        signal.signal(sig, clean)    
    mainthrd1 = threading.Thread(target=iWorker2, args=(idT))
    mainthrd1.daemon=True
    mainthrd1.start()    
    do_work1(0, False)

clean()






    