import websocket
import asyncio
import time
import threading
import subprocess
import requests
import json
#import rel
from datetime import datetime
import xml.etree.ElementTree as ET


#websocket.enableTrace(True)
socketurl = "wss://iptv.fleex.gr/ws"
playFlag = 0
playStream = ""
 
def on_message(wsapp, message):
    print(message)
    
    if message == "refresh":
        DownloadPlaylist()
        
    pass
 
 
def on_open(wsapp):
    print(f'{str(datetime.now())}   ### ONLINE ###')
    wsapp.send('{"cmd":"login","model":"fbx3566w","sn":"0987654321"}')
 
 
def on_close(wsapp, close_status_code, close_msg):
    print(f'{str(datetime.now())}   ### OFFLINE ###')
    print(close_msg)
    time.sleep(10)
    wsapp.run_forever(ping_interval=40, ping_timeout=30)
    
    #rel.abort()
    #wsapp.run_forever(dispatcher=rel, ping_interval=40, ping_timeout=30)
    #rel.signal(2, rel.abort)
    #rel.dispatch()
 
 
def on_error(wsapp, error):
    print(f'{str(error)}   ### ERROR ###')
 
 
def on_ping(wsapp, message):
    #print(f'{str(datetime.now())}   ### Got a Ping! ###')
    a = 1
 
 
def on_pong(wsapp, message):
    #print(f'{str(datetime.now())}   ### Send a Pong! ###')
    a = 2





def DownloadPlaylist():
    global playFlag
    global playStream
    
    url = 'https://iptv.fleex.gr/site/content'
    myobj = {'secret_key': 'T5cuhDpwkUe2x39F', 'serial': '0987654321'}
    
    status = subprocess.call('php /data/firmware/htdocs/DS/devicestatus.php', shell=True)

    try:
        x = requests.post(url, json = myobj)

        print(x)
        obj1 = x.json()
        print(obj1)
        
        playFlag = 0
        
        if len(obj1) >= 1:
            print("check1")
            
            try:
                print("check2")
                obj2 = json.loads(obj1["html"])
            except:
                print("check3")
                obj2 = json.loads(obj1[0]["html"])
            
            print("check4")
            xml=ET.fromstring(obj2[0]["html"])

            #print(obj2[0]["html"])
            #v = xml.find('.//div').attrib['data-audiosrc']
            
            for elem in xml.findall(".//*[@data-tvsrc]"):
                v = elem.attrib["data-tvsrc"]
            
            
            if len(v) > 5:
                
                playFlag = 1
                
                if v != playStream:
                    print("kill previous gst-launch and start a new one")
                    print (v)
                    status = subprocess.call('pkill gst-launch-1.0 -9', shell=True)
                    playStream = v
                    status = subprocess.call('gst-launch-1.0 playbin uri="' + playStream + '" volume=0.3 &', shell=True)
                
            
    except Exception as e:
        print(e.message)
        playFlag = 0
        status = subprocess.call('pkill gst-launch-1.0 -9', shell=True)
        print("request error")
        
        
        

def ptimer():
    global playFlag
    global playStream
    
    while True:
        
        gstRun = 0
        try:
            result = subprocess.check_output('pidof gst-launch-1.0', stderr=subprocess.STDOUT, shell=True)
            gstRun = 1
        except:
            gstRun = 0
            
        if playFlag == 1 and gstRun == 0:
            print("force play again")
            status = subprocess.call('gst-launch-1.0 playbin uri="' + playStream + '" volume=0.3 &', shell=True)
            
        if playFlag == 0 and gstRun == 1:
            print("force stop")
            status = subprocess.call('pkill gst-launch-1.0 -9', shell=True)
        
        time.sleep(3)
        




def htimer():
    global playFlag
    global playStream
    
    while True:
        print("Check for new content - Timer fired")
        DownloadPlaylist()
        
        time.sleep(60)




wsapp = websocket.WebSocketApp(socketurl,
                               on_open=on_open,
                               on_message=on_message,
                               on_error=on_error,
                               on_close=on_close,
                               on_ping=on_ping,
                               on_pong=on_pong)

status = subprocess.call('pactl set-sink-volume 0 100%', shell=True)
#status = subprocess.call('pactl set-sink-volume 17 100%', shell=True)

threading.Thread(target=htimer).start()
threading.Thread(target=ptimer).start()

wsapp.run_forever(ping_interval=40, ping_timeout=30)
#rel.signal(2, rel.abort)  # Keyboard Interrupt
#rel.dispatch()
