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

from CTerm import *
import re
from sitestatus import *
from ct_system import *
from cterm_command import *

# send to current window
def SendString0(s):
	ID=GetSessionID()
	if ID and IsConnected(ID):
		SendString(ID, s)

favorcmd="\x1b[D\x1b[D\x1b[D\x1b[D\x1b[D\x1b[D\x1b[D\x1b[D\x1b[D\x1b[DF\n"
maincmd="  \x1b[D\x1b[D\x1b[D\x1b[D\x1b[D\x1b[D\x1b[D\x1b[D\x1b[D\x1b[DF"
def GotoBoardSimple(boardname, ID=None):
	#print 'GotoBoardSimple'
	if ID==None:
		ID=GetSessionID()
		if not ID:
			return
	if not IsConnected(ID):
		return
	sitetype=GetSiteType(ID)
	SendString(ID,maincmd)		
	if sitetype==ST_SMTH: # or 其它支持S选择的站
		SendString(ID,'S\n')
		addr=GetHostAddress(ID)
		if addr.find("bbs.gscas.ac.cn")!=-1 or addr.find('kyxk')!=-1: #kyxk等站有个二级菜单
			SendString(ID,'S\n')
		SendString(ID,boardname+'\n ')
	else:
		allboardcmd='E\nB'
		if sitetype==ST_MAPLE:
			allboardcmd='B'
		else:
			#s=GetText(ID,0)
			#if s.find('白云黄鹤')!=-1:
			sitename=GetSessionName(ID)
			if sitename.find('白云黄鹤')!=-1: #其它特殊FB站在这里加
				allboardcmd='G\nG\n'
			else:
				allboardcmd='E\nB\n'
		SendString(ID,allboardcmd+'/'+boardname+'\n\n')
	#WaitFor(ID, SST_LIST, SST_LIST_ARTICLE, 1, True)

def GotoBoardArticle(boardname, title):
	#print 'GotoBoardArticle'
	ID=GetSessionID()
	if not ID:
		return
	GotoBoardSimple(boardname, ID)
	if GetSiteType(ID)==ST_YTHT:	
		s=GetText(ID, GetTermHeight(ID)-1)
		if s.find( "您初次" )!=-1: #您初次访问本版, 是否首先察看精华区? (选A不再做此提示)(Y/N/A) [Y]:
			SendString(ID, "n\n")
#			dataEvents[ID].wait()
	SendString(ID, " 1\n\x1b[A?"+title+"\n=\n") #ith@smth

# 查看十大，程序调用
def ViewHotArticle(nLine):
	#print 'ViewHotArticle'
	ID=GetSessionID()
	if not ID:
		return
	
	addr=GetHostAddress(ID)
	if addr.find("bbs.gscas.ac.cn")!=-1 or addr.find('kyxk')!=-1: #kyxk现在支持直接看了
		s=GetText(ID, GetTermHeight(ID)-1)
		if s.find('[1-0]')!=-1:	#[1-0]和上下键选择阅读, 右键进入, 其他键退出...
			idx=(nLine-2)/2+1 #2-21
			SendString(ID, str(idx)+"\n");
			return
	elif addr.find("newsmth")!=-1:
		idx=(nLine-2)/2+1 #2-21
		SendString(ID, str(idx)+"\n");
		return

	ret=False
	while True:
		line=GetText(ID, 0)
		if line.find("本日十大")==-1:
			break
		#取版名，标题
		if nLine % 2 == 1:
			i=nLine-1
			j=nLine
		else:
			i=nLine
			j=nLine+1
			
		line=GetText(ID, i)
		idx=line.find("信区 : ")
		if idx!=-1:
			idx+=7; #sizeof "信区 : "
		else:
			break
				
		idx1=line.find(' ', idx)
		boardname=line[idx : idx1]
		if len(boardname) == 0:
			break
	
		line=GetText(ID, j)
		idx=line.find("标题 : ")
		if idx!=-1:
			idx+=7; #sizeof 标题 : 
		else:
			break
				
		title=line[idx : len(line)].rstrip()
		#print 'title: ', title
		if len(title)==0:
			break
	
		ret=True
		GotoBoardArticle(boardname, title)
		break
	if not ret:
		SendString(ID, '\n') # not hot, just SST_ENTER
	
def SendStringList(ID, s):
	if type(s)==list:
		for item in s:
			SendString(ID, item)
			#print 'sent ', item
			if dataEvents.has_key(ID):
				dataEvents[ID].wait()
				#print 'get response'
				#print GetText(ID, CaretY(ID))
	else: #str
		SendString(ID, s)

# 确认你要wait的状态一定会出现，否则。。。
def WaitFor(ID, nStatus=None, nSub=None, timeout=1, bAutoEnter=False, bNext=True):
	count=0
	if bNext:
		#print 'waiting next status'
		dataEvents[ID].wait(timeout)
	while True:
		if count>20:
			print '掉线了？或程序有误？' #若无误，增大该计数上限再试
			return False
		st=GetStatus(ID)
		#print 'status', st
		if st==None:
			return False # maybe closed
		elif st!=nStatus:
			#print 'no. we expect: ', nStatus
			#print "status:%d"%st
			if bAutoEnter:
				if st==SST_ENTER:
					SendString(ID,'\n')
				elif st==SST_ARTICLE:
					SendString(ID,'R\n')
		elif nSub:
			sub=GetSubStatus(ID)
			if sub==nSub:
				#print 'got it!'
				return True
		else:
			#print 'got it!'
			return True
		dataEvents[ID].wait(timeout)
		count+=1
		if nStatus==None:
			return True
def GotoFavor(ID):
	sitetype=GetSiteType(ID)
	if sitetype==ST_MAPLE:
		return

	SendString(ID,favorcmd)
	WaitFor(ID,SST_LIST,SST_LIST_BOARD)
	str0=GetText(ID,0)
	if GetSiteType(ID)==ST_SMTH:
		#print 'is smth site'
		if str0.find('讨论区列表')!=-1: #smth. FB无法分辨
			WaitFor(ID,SST_LIST,SST_LIST_BOARD)
			str0=GetString(ID,0)
	if ( sitetype==ST_SMTH and str0.find('个人定制区')==-1 ) or ( sitetype==ST_FIREBIRD and str0.find('讨论区列表')==-1 ):
		#print str0
		#print 'something wrong!'
		return False
	else:
		#print 'favoriate comes'
		return True

boardexp=r"^\s*(>?)(\d+)  ([^\s][^\s]) ([A-Za-z]+)\s*\[([^\s]*?)\] ([^\s][^\s]) (.+)\s+([a-zA-Z\d]+)\s*$"
def GetBoardList(ID, expectboard=None):
	termheight=GetTermHeight(ID)
	st=GetStatus(ID)
	sub=GetSubStatus(ID)
	if st!=SST_LIST or sub!=SST_LIST_BOARD:
		return
	else:
		boardlist=[]
		for i in range(3,termheight):
			str0=GetText(ID,i)
			#print '%d:%s'%(i,str0)
			matchobj=re.match(boardexp,str0)
			if matchobj:
				boardname=matchobj.group(4)
				#print boardname
				if expectboard:
					#print '%d: %s ? %s'%(i,boardname,expectboard)
					#print expectboard==boardname
					if expectboard==boardname:
						return i
				else:
					boardlist.append(boardname)
				#print matchobj.groups()
			else:
				break
		if expectboard:
			return -1 # not found
		else:
			return boardlist

def GotoBoard(boardname, ID=None):
	if not ID:
		ID=GetSessionID()
		if not ID:
			return
	GotoBoardSimple(boardname, ID)
	
# for FB
def GotoBoardFB(ID, boardname):
	termheight=GetTermHeight(ID)
	sitetype=GetSiteType(ID)
	if sitetype==ST_MAPLE:
		return

	if GotoFavor(ID):
		i=GetBoardList(ID, boardname)		
		if type(i)==int and 3<=i and i<=(termheight-2):
			SendString(ID,str(i-2)+'\n\n')
			WaitFor(ID,SST_LIST,SST_LIST_ARTICLE)
		else:
			print 'not found '+boardname

# need:
# 0: title
# 1: writer
def GetTitle(ID, need=0):
	'''分析文章标题。返回值：文章号，作者'''
	#print 'in GetTitle'
	status=GetStatus(ID)
	sub=GetSubStatus(ID)
	str1=''
	if status==SST_ARTICLE or status==SST_END or status==SST_ENTER:
		s1=GetText(ID,0)
		if s1[0:8]!='发信人: ':
			return
		s2=GetText(ID,1)		
		if s2[0:8]!='标  题: ':
			return
		if need==0:
			return s2[8:len(s2)].strip()
		elif need==1:
			s=s1.split()
			return s[2]
	elif status!=SST_LIST or sub!=SST_LIST_ARTICLE: # list, Article list
		#print '不是文章列表.%d, %d'%(status,sub)
		return
	else:
		n=CaretY(ID)
		str1=GetText(ID, n)
		#print 'caret y:%d'%n
		#>  722   nullspace    Aug 30  ● 70580.934517只青蛙70580.934517张嘴
		#>2357   nullspace    Oct  9  ◆ sd
		exp=r'^(>)?\s*(\d*|\[.{4}\])\s*([\+\*NmMgGbB])?\s*(\w*)\s*(\w*)\s*(\d*)(?:\.)?(?:x|@|\s+)?(● |◆ |Re: )(.*[^s])\s*$'
		matchobj=re.match(exp, str1)
		if matchobj:
			#print 'str1 is "%s"'%str1
			#print	matchobj.groups()
			#return (matchobj.group(2), matchobj.group(4), matchobj.group(7), matchobj.group(8))  # article no.
			if need==0:
				title=''
				if matchobj.group(7)=='Re: ':
					title+='Re: '
				title+=matchobj.group(8)
				#print title.strip()
				return title.strip()
			elif need==1:
				return matchobj.group(4)
		else:
			print 'str1 is "%s"'%str1
			print 'not matched'

	

#exit str for 无名小站
exitstr1=["\x1b[D"]*10
exitstr1.extend(["\n",'g',"\n","\n","\n","\n"])
#use command:
#ID=GetSessionID()
#SendStringList(ID,exitstr1)

# 快速离站(程序调用)
def QuickAway(ID=None, bAutoMailBack=False):
	if not IsConnected(ID):
		return
	if ID==None:
		ID=GetSessionID();
	if not ID:
		return

	sitename=GetSessionName(ID)
	if sitename.find('Big5')!=-1:
		QuickAwayBig5(ID)
	else:
		mailcmd=''
		if bAutoMailBack:
			mailcmd='M'	#加M是为把信息寄回信箱
		exitstr="\x1b[D\x1b[D\x1b[D\x1b[D\x1b[D\x1b[D\x1b[D\n\nq%s\n\n\n"%mailcmd

		if sitename.find('无名小站')!=-1:
			SendStringList(ID,exitstr1)
			return
		status=GetStatus(ID)
		if status==SST_CHATROOM:
			if st==ST_MAPLE:
				SendString(ID, "/bye\n\n")
			else:
				SendString(ID, "\4") #^D
		elif status==SST_TALK:
			if st==ST_MAPLE:
				SendString(ID, "\3\3\n\n") #^C
			else:
				SendString(ID, "\4")
		elif status==SST_WRITE:
			SendString(ID, "\x18\n\n") #^W
		SendString(ID, exitstr)

def QuickAwayBig5(ID):
	exitstr="\x1b[D\x1b[D\x1b[D\x1b[D\x1b[D\x1b[D\x1b[D\ry\rg\r\r"
	SendString(ID, exitstr)

def GotoDigest():
	ID=GetSessionID()
	if ID:
		st=GetStatus(ID)
		sub=GetSubStatus(ID)
		if st==SST_LIST and sub==SST_LIST_ARTICLE:
			sitetype=GetSiteType(ID)
			if sitetype==ST_MAPLE:
				SendString(ID,'\t')
			elif sitetype!=ST_NORMAL:
				SendString(ID,'x')
# send string to current window
def SendStringTo(s):
	ID=GetSessionID()
	if ID:
		SendString(ID,s)

#18;		ctrl+alt+c;			clear;		true;	py:ID=CTerm.GetSessionID()\nst=CTerm.GetSiteType(ID)\nif st==3:\n\tCTerm.SendString(ID,'f')\nelif st==4:\n\tCTerm.SendString(ID,'ff')\nelif st!=0:\n\tCTerm.SendString(ID,'c'); 
#清除未读
def ClearReadFlag():
	ID=GetSessionID()
	tp=GetSiteType(ID)
	if tp==ST_SMTH:
		SendString(ID,'f')
	elif tp==ST_YTHT:
		SendString(ID,'ff')
	elif tp!=ST_NORMAL:
		SendString(ID,'c'); 

def ReplyPost():
	ID=GetSessionID()
	if ID:
		nStatus=GetStatus(ID)
		sub=GetSubStatus(ID)
		if  nStatus==SST_ARTICLE:
			SendString(ID,'q')
		WaitFor(SST_END)
		st=GetSiteType(ID)

		#判断不可re
		if st==ST_MAPLE:
			s=GetText(ID,23)
			if s.find('不可回应')!=-1:
				return
		SendString(ID,'r')
		WaitFor(ID)
		#fb:对不起, 该文章有不可 RE 属性, 你不能回复(RE) 这篇文章.
		#smth:很抱歉，本文已经设置为不可re模式,请不要试图讨论本文...
		#maple:前面带0，end时状态栏有“不可回应”字样，re时直接返回
		if st==ST_SMTH:
			s=GetText(ID,5)
			if s.find('不可 RE 属性')!=-1:
				return
		elif st==ST_FIRBIRD:
			s=GetText(ID,2)
			if s.find('不可re模式')!=-1:
				return

		#elif st==ST_YTHT:
		SendString(ID,'\n')
		if st==ST_MAPLE:
			SendString(ID,'\n\n\n')
			
def SuperPaste():
	ID=GetSessionID()
	if ID:
		nStatus=GetStatus(ID)
		nSub=GetSubStatus(ID)
		if nStatus==SST_LIST and nSub==SST_LIST_ARTICLE:
			SendCommand(ID_EDIT_PASTE)

# from qterm-0.3.8
# This works only for smth.org, make appropriate changes according
# to each BBS site. 
def AutoReply(ID):
	# not message
	if(CaretY(ID)!=2):
		return
	text = GetText(ID,0)
	# sender
	lst = text.split()
	sender = lst[0] 

	# who am i, this works when user ID in status bar
	# so better set yourself
	# text = GetText(ID,rows(ID)-1)
	#lst = string.split(text,"]")
	#text = lst[2]
	#lst = string.split(text,"[")
	#me = lst[1]
	me = "kingson"
	msg = GetText(ID,1)
	reply="i am "+me+"'s autoreply script, can i help you?"

	if(msg.find("ft")!=-1):
		reply = sender+" ,why ft?"
	elif(msg.find("怎么")!=-1 or msg.find("为什么")!=-1):
		reply = "我也不知道耶"

	SendString(ID,"r")
	SendString(ID,reply)
	SendString(ID,"\n")

# from qterm-0.3.8
# get the current user ID
# only for FireBird BBS
def GetCurrentUser():
	ID=GetSessionID()
	text = GetText(ID,23)
	if(text.find("使用者")==-1):# wrong status
		return
	lst = string.split(text,"]")
	text = lst[2]
	lst = string.split(text,"[")
	return lst[1]

# 下面两个函数cterm调用
def LockBBS():
	ID=GetSessionID() #active
	LockBBSScreen(ID)
	# if you want to lock all connected sites, write code like this:
	#count=GetSessionNum()
	#for i in range(count):
	#	ID=GetSessionID(i)
	#	if ID:
	#		LockBBSScreen(ID)
def UnlockBBS():
	ID=GetSessionID() #active
	UnlockBBSScreen(ID)
	#count=GetSessionNum()
	#for i in range(count):
	#	ID=GetSessionID(i)
	#	if ID:
	#		UnlockBBSScreen(ID)

def LockBBSScreen(ID=None):
	if ID==None:
		ID=GetSessionID()
		if ID==None:
			print 'no active window'
			return
	if not IsConnected(ID):
		return
	status=GetStatus(ID)
	if status!=SST_WRITE and status!=SST_TALK and status!=SST_CHATROOM:
		SendString(ID, "\x1b[D\x1b[D\x1b[D\x1b[D\x1b[D\x1b[D\x1b[D\x1b[D\x1b[D\x1b[D")	#跳到主菜单
		if GetSiteType(ID)==ST_MAPLE:
			SendString(ID, "U\nL\n");
		else:
			SendString(ID,"I\nL\nCTerm 锁定\n\n"); #瀚海特殊 sixue1999@newsmth
	else:
		print 'please save your edit first before locking bbs.'
	
def UnlockBBSScreen(ID=None):
	if ID==None:
		ID=GetSessionID()
	if not IsConnected(ID):
		return
	pw=GetLoginPW(ID)
	if pw:
		#print pw
		y=CaretY(ID)
		s=GetText(ID,y)
		if s.find('输入')==-1 or s.find('密码')==-1:
			return
		status=GetStatus(ID)
		if status!=SST_WRITE and status!=SST_TALK and status!=SST_CHATROOM:
			if GetSiteType(ID)==ST_MAPLE:
				SendString(ID,pw+"\n\x1b[D") # favoriate
			else:
				SendString(ID,pw+"\n\x1b[DF")

from postmilti import *
def uponefile(fn):
	ID = GetSessionID()
	if ID and ID != -1:
		url = GetText(ID, 1).strip()
		#print fn
		postfile(url, fn)