from PIL import Image
import numpy as np
import cv2
import base64
import io,os
import requests
import time,json
import string,random
import glob
##for CeKanYuan
def get_offlineUrls(taskUrl,offlineFile,jsonfile='SendLog/platformQueryOfftask.json'):
    with open(offlineFile,'r') as fp:
        lines=fp.readlines()
        doneCodes=[line.strip().split(' ')[2] for line in lines]
    try:
        res = requests.get(taskUrl,timeout=10).json()
        offlines=res['data'] ##offlines[0]['code'],offlines[0]['videoUrl']   
        with open(jsonfile,'w') as fp:
            json.dump(res,fp, ensure_ascii=False)    
    except  Exception as ee:
        timestr=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) 
        print('###line43 %s read taskUrl:%s error:%s '%(timestr,taskUrl,ee))  
        offlines=[]
    outOfflines=[] 
    for off in offlines:
        off['port']=1935;
        off.update({'name':'off-' +off.pop("code")})
        if off['name'] in doneCodes:
            continue
        off.update({'url': off.pop("videoUrl")})
        outOfflines.append(off)
        #off['url']=off['videoUrl']

    return outOfflines
def platurlToJsonfile(taskUrl,jsonfile='SendLog/platformQuery.json'):
    try:
        res = requests.get(taskUrl,timeout=10).json()
        offlines=res['data'] ##offlines[0]['code'],offlines[0]['videoUrl']   
        with open(jsonfile,'w') as fp:
            json.dump(res,fp, ensure_ascii=False)
    except  Exception as ee:
       timestr=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) 
       print('###line43 %s read taskUrl:%s error:%s '%(timestr,taskUrl,ee))            
                 
def get_websource_fromTxt(txtfile):
    with open(txtfile,'r') as fp:
        lines = fp.readlines()
    sources=[ ]
    for line in lines:
        sous={}
        try:
            sps = line.strip().split(' ')
            sous['url']=sps[0];sous['port']=sps[1]
            
            #webs.append(sps[0])
            if 'rtmp' in sps[0]:
                name = sps[0].split('/')[4]
                
            else:
                name = sps[0][-3:]
            sous['name']='live-'+name.replace('_','')
            sous['port']=sps[1]
            sources.append(sous)
        except Exception as ee:

            print('####format error : %s, line:%s , in file:%s#####'%(ee,line,txtfile))
    assert len(sources)>0
    return sources
    
def update_websource_offAndLive(platform_query_url,sourceFile,offlineFile,jsonfile='SendLog/platformQuery.json'):
 
    #platform_query_url='http://47.96.182.154:9051/api/suanfa/getPlatformInfo'
    txtSource=get_websource_fromTxt(sourceFile)
    try:
        res = requests.get(platform_query_url,timeout=10).json()    
        questionUrl = res['data']['questionUrl']  ###直播流时，问题图片的推送地址
        offlineUrl = res['data']['offlineUrl']  ###http离线视频时，问题图片的推送地址
        taskUrl = res['data']['taskUrl'] ###http离线视频时，离线视频存放的地址
        with open(jsonfile,'w') as fp:
            json.dump(res,fp, ensure_ascii=False)    
    except Exception as ee:
        timestr=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        print('######line83: %s: file:geturlPlatform: error %s ,url:%s #####'%(timestr,ee,platform_query_url))        
        taskUrl='http://121.40.249.52:9050/api/analyse/getAiInspectionList'
    if taskUrl:        
        offlines=get_offlineUrls(taskUrl,offlineFile)
        txtSource.extend(offlines)
    #[{'url': 'rtmp://demoplay.yunhengzhizao.cn/live/THSA_HD5M', 'port': '1935', 'name': 'live-THSAHD5M'}]
    outlist=[]    
    for sourss in  txtSource :
        source_url = sourss['url']
        vid = cv2.VideoCapture(source_url)
        if vid.isOpened():
            outlist.append( sourss  )
    return outlist    
    #print('##line65:',txtSource)    
       

    
if __name__=='__main__':
    platform_query_url='http://47.96.182.154:9051/api/suanfa/getPlatformInfo'
    sourceFile='../config/source.txt'
    offlineFile='../mintors/offlines/doneCodes.txt'
    jsonfile='../SendLog/platformQuery.json'
    txtSource=update_websource_offAndLive(platform_query_url,sourceFile,offlineFile,jsonfile=jsonfile)
    print(txtSource)
