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

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

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

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

# filenames
iav_statfile_n="iav_ctl"
iav_logfile_n="iav_log"

# file path
iav_statfile="iav_ctl.txt"
iav_logfile="iav_log.txt"


# r 書き込み専用 
# w 書き込み専用 
# a 追加(ファイルを開く時、ファイルの参照点は自動的にファイルの末尾に移動) 
# r+ 更新(読み取りと書き込み) 
# w+ ファイルを空にした後、そのファイルを読み書き用に開く 
# a+ ファイルを読み書き用に開く、参照点は自動的にファイルの末尾に移動 
# b 他のオプションと一緒に指定すると、ファイルをバイナリモードで開く 

def init (temp_path,sess_id):
	global fp_dbg,fp_ctl
	global iav_logfile,iav_statfile
	
	if not os.path.exists(temp_path):
		os.makedirs(temp_path)

	iav_logfile=temp_path+"/"+iav_logfile_n+"("+sess_id+").txt"
	iav_statfile=temp_path+"/"+iav_statfile_n+"("+sess_id+").txt"
	
	if(fp_dbg is None):
		if(os.path.isfile(iav_logfile)):
			fp_dbg=open(iav_logfile,"r+")
		else:
			fp_dbg=open(iav_logfile,"w+")
	if(fp_ctl is None):
		if(os.path.isfile(iav_statfile)):
			fp_ctl=open(iav_statfile,"r+")
		else:
			fp_ctl=open(iav_statfile,"w+")

def getErrorMsg (reset):
	global ErrorMsg
	str=ErrorMsg
	if(reset):
		ErrorMsg=None
	return str
	
def 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
	
#---- set pos to play next
def setnxpos (mpos,spos,mmax=None):
	#pass
	global fp_ctl
	if(mmax!=None):
		if(spos>=mmax):
			spos=0
		if(mpos>=mmax):
			mpos=0
	#fp_ctl.seek(0,2)
	print >>fp_ctl, "mpos=%d, spos=%d, time=%f" % (mpos,spos,time.time())
	fp_ctl.flush()

#---- get pos to play next
def getnxpos (mode,listsz,clippath,imgpos):
	global fp_ctl,iav_statfile
	mpos=0
	spos=-1
	imgpos_prev= -1
	mpos_top=0
	cnt=0
	clippath_prev=None
	fp_ctl.seek(0,0)
	for line in fp_ctl:
		pos=line.find("clippath=")
		if(pos>=0):
			str=line[pos+9:]
			ar=str.rsplit("?",2)
			clippath_prev=ar[0].strip()
			dbg("getnxpos1: found clippath_prev=%s" % (clippath_prev))
			if(len(ar)>1):
				imgpos_prev=int(ar[1])
			continue
		pos=line.find("mpos=")
		if(pos>=0):
			#dbg("getnxpos1: found mpos, line=%s" % (line))
			cnt+=1
			str=line[pos+5:]
			ar=str.split(",")
			mpos=int(ar[0])
			if(cnt==1):
				mpos_top=mpos
		pos=line.find("spos=")
		if(pos>=0):
			str=line[pos+5:]
			ar=str.split(",")
			spos=int(ar[0])
		if(mode==0 and cnt>0):
			# get first line
			break

	dbg("getnxpos1: found mpos=%d, spos=%d, imgcnt=%d" % (mpos,spos,listsz))
	dbg("getnxpos1: imgpos_prev=%d, imgpos=%d" % (imgpos_prev,imgpos))
	dbg("getnxpos1: clippath     =%s" % (clippath))
	dbg("getnxpos1: clippath_prev=%s" % (clippath_prev))

	if(clippath_prev is None or clippath!=clippath_prev):
		#path changed
		mpos=0
		spos=0
	elif(spos<0):
		spos=imgpos_prev;
		mpos=0
	else:
		spos +=1
					
	#--- min check
	if(spos<0):
		spos=0	
	if(mpos<0):
		mpos=0	
	
	#--- max check
	if(mpos>=listsz):
		mpos=0
	if(spos>=listsz):
		spos=0
	
	#--- reopen & init
	if(True):
		fp_ctl.close()
		fp_ctl=open(iav_statfile,"w+")
		print >>fp_ctl,"clippath=%s?%d" % (clippath,spos)
		setnxpos(mpos,spos)
	
	dbg("getnxpos: found mpos=%d, spos=%d, imgcnt=%d" % (mpos,spos,listsz))
	return (mpos,spos)

def 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")
		#fp=codecs.open(clippath,"r")
		for line in fp:
			#line=line.strip().decode("utf_8")  # to make encode same as glob.glob
			line=line.strip()
			if(not line.startswith('#') and len(line)>0):
				try:
					#f=line.encode(gs_encode_sys)
					f=line
					# can't check media_type when entry isn't local (ex. url)
					list.append(f)
				except :
					dbg("getAudiolist : encode error, clippath=%s" % (line))
					pass
		fp.close()
		#dbg("getAudiolist=%r" % list)
		return list
	
	elif(os.path.isdir(clippath)):
		#list0=glob.glob(unicode(clippath+"/*.*"))  #unicode(): for process unicode file name
		path=os.path.join(clippath,u"*.*")
		list0=glob.glob(path)
		#list0=os.listdir(clippath)
		#for i in range(len(list0)):
		#	list0[i]=list0[i].decode(gs_encode_sys)
	else:
		return list
		
	for f in list0:
		lf=f.lower()
		
		#uf=f.decode(gs_encode_sys)
		uf,enc=conv_encoding(f)
		#uf=win32api.GetShortPathName(uf)   # to pass unicode path name
		
		if(isAudio(lf)):
			list.append(uf)
		elif(isVideo(lf)):
			# will be extracted audio from
			list.append(uf)
		elif(lf.endswith((".cca",".mp4"))):
			list.append(uf)
		elif(lf.endswith((".pxm"))):
			#pxm is meta-file, get target file's path written in pxm
			dbg("getAudiolist: pxm found, type=%r file=%r" % (type(f),f))
			fp=open(f,"r")
			for line in fp:
				line=line.strip()
				if(not line.startswith("#") and len(line)>0):
					f=None
					if(f==None):
						pos=line.find("path=")
						if(pos>=0):
							f=line[pos+len("path="):].strip('\"\' ')
					if(f==None):
						pos=line.find("path_vf=")
						if(pos>=0):
							f=line[pos+len("path_vf="):].strip('\"\' ')
					if(f!=None):
						uf,enc=conv_encoding(f)
						if(isWebVideo(uf)):
							list.append(uf)
						elif(os.path.isfile(uf)):
							if(isAudio(uf)):
								list.append(uf)
							elif(isVideo(uf)):
								list.append(uf)
			fp.close()
	#for i in range(len(list)):
	#	list[i]=list[i].decode(gs_encode_sys)

	dbg0("getAudiolist=%r" % list)
	return list


#----------------------------------------------------------------------------------
# main for test
#----------------------------------------------------------------------------------
if __name__ == '__main__':
	
	if(True):
		dbg("==== RzIAVsubs Test main executed!! ==============")
		clippath="C:/Documents and Settings/papa/My Documents/My Pictures/tv"
		clippath="C:/Documents and Settings/papa/My Documents/My Pictures/SceneTest"
		clippath=="C:/Documents and Settings/papa/My Documents/My Pictures/SceneClips"
		test=1
		
		fp=open("wk.log","w")
		if(len(sys.argv)>=2):
			test=int(sys.argv[1])
		if(len(sys.argv)>=3):
			clippath=sys.argv[2]

		print >>fp, "type=%d clippath=%s" % (test,clippath)
		
		if(test==1):
			print >>fp, "getPlaylist path=%s" % (clippath)
			(type,list,mpos,spos,mmax)=getPlaylist(clippath)
			for f in list:
				print >>fp, f
			print >>fp, "type=%s, list count=%d, mpos=%d, spos=%d" % (type,len(list),mpos,spos)
		elif(test==2):
			print >>fp, "getFilelist path=%s" % (clippath)
			list=getFilelist(clippath,"name")
			for f in list:
				print >>fp, f
			print >>fp, "list count=%d" % (len(list))
		fp.close()
