#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os, sys, time
import glob
import codecs
import ctypes

sys.path.append('regzamod')
from Common.RzCmnSubs import dbg,dbg2,dbg0,error,setdbg,conv_encoding
from Common.RzCmnSubs import isAudio,isImage,isVideo,isWebVideo,isWebContents
from Common.RzCmnSubs import gs_encode_sys,gs_debug,gs_verbose,gs_ff_loglev,gs_prog_ytdl,gs_prog_ytdl_s

#--- global commons (don't change here: declared in Common.RzCmnSubs)
#gs_encode_sys="utf-8"  # text encode type of system environ
#gs_encode_sys="cp932"  # text encode type of system environ 

fp_ctl=None		#pos controll file descripter
fp_dbg=sys.stderr
ErrorMsg=None

# filenames
web_statfile_n="web_ctl"
web_logfile_n="web_log"

# file path
web_statfile="web_ctl.txt"
web_logfile="web_log.txt"

def ws_init (temp_path,sess_id):
	global fp_dbg,fp_ctl
	global web_logfile,web_statfile
	
	if not os.path.exists(temp_path):
		os.makedirs(temp_path)

	web_logfile=temp_path+"/"+web_logfile_n+"("+sess_id+").txt"
	web_statfile=temp_path+"/"+web_statfile_n+"("+sess_id+").txt"
	
	if(fp_dbg is None):
		if(os.path.isfile(web_logfile)):
			fp_dbg=open(web_logfile,"r+")
		else:
			fp_dbg=open(web_logfile,"w+")
	if(fp_ctl is None):
		if(os.path.isfile(web_statfile)):
			fp_ctl=open(web_statfile,"r+")
		else:
			fp_ctl=open(web_statfile,"w+")

def ws_getErrorMsg (reset):
	global ErrorMsg
	str=ErrorMsg
	if(reset):
		ErrorMsg=None
	return str
	
def ws_error_dp (disp,*arg):
	global ErrorMsg
	header="RzIAVplayer [ERROR]:"
	str=header+''.join(arg)
	dbg0(str)
	if(disp): # disp error message on renderer screen
		ErrorMsg=str
	#print >>sys.stderr, ErrorMsg

def ws_getAudiolist (clippath):
	list=[]
	dbg("getAudiolist Start: clippath=%s" % (clippath))
	if(os.path.isfile(clippath)):
		#dbg("getFilelist: is File")
		#dbg("sys.getdefaultencoding=%s" % sys.getdefaultencoding())
		fp=codecs.open(clippath,"r","utf_8")
		for line in fp:
			line=line.strip()
			if(not line.startswith('#') and len(line)>0):
				f=line  # is unicode text
				list.append(f)
		fp.close()
		return list		
	elif(os.path.isdir(clippath)):
		cliplist=glob.glob(os.path.join(clippath,"*.*"))
		# glob seems to return shift-jis text --> convert to unicode text
		#for i in range(len(cliplist)):
		#	cliplist[i]=cliplist[i].decode(gs_encode_sys)
	else:
		return list
		
	for f in cliplist:
		lf=f.lower()
		uf=f.decode(gs_encode_sys)
		if(isAudio(lf)):
			list.append(uf)
		elif(isVideo(lf)):
			# will be extracted audio from
			list.append(uf)
		elif(isWebVideo(lf)):
			# will be extracted audio from
			list.append(uf)
		elif(lf.endswith((".cca"))):
			list.append(uf)
		elif(lf.endswith((".pxm"))):
			#pxm is meta-file, get target file's path written in pxm
			fp=open(f,"r")
			for line in fp:
				line=line.strip()
				if(not line.startswith("#") and len(line)>0):
					pos=line.find("path=")
					if(pos>=0):
						f=line[pos+5:].strip('\"\' ')
						uf,enc=conv_encoding(f)
						if(os.path.isfile(f) and isAudio(f)):
							list.append(uf)
			fp.close()
	return list

# create ffmpeg concat file (for audio concat,max)
def ws_mkconcat (alist,spos,concatf,max):

	list=[]
	p=spos
	mod=len(alist)
	line=alist[p]
	extruct=0
	if(not line.startswith("http")):
		msfx=line.rsplit(".",2)
		if(len(msfx)==2):
			extruct=1
	if(extruct):
		#---- extruct only same-suffix entries
		# ffmpeg seems can't handle different-suffix files in concat
		sfx=msfx[1].lower()
		#dbg("ws_concat: sfx=%s" % sfx)
		for i in range(mod):
			p1=p % mod
			line=alist[p1]
			if(line.lower().endswith(sfx)):
				list.append(line)
			p+=1
	else:
		for i in range(mod):
			p1=p % mod
			line=alist[p1]
			list.append(line)
			p+=1
	
	#---- write to concat file
	fp=codecs.open(concatf,"w","utf-8")
	mod=len(list)
	p=0
	for i in range(max):  # (0 to max-1)
		p1=p % mod
		line=list[p1]
		#replace ['] in path_name to ['\''], for ffmpeg concat 
		line=line.replace("'","'\\''")
		print >>fp, "file '%s'" % line
		p+=1
	fp.close()
	

