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

# CopyArticle.py

import sys,string,re
from CTerm import *
from tools import *

#且去掉文字末尾多余的回车,空行
def dropCR(text):
	str_list=text.split('\n')
	linecount=len(str_list)
	reexp=re.compile(r'^\s*$')
	for i in range(linecount):
		rematch=re.match(reexp,str_list[-(i+1)])
		if not rematch:
			break
	return string.join(str_list[0:linecount-i], '\n')

# 下载文章
# savetype:
# 0: 文本
# 1: ansi
# 2: html
def copyArticle(ID, savetype=0):
	#返回光标所在处的文章内容
	data=''
	title=''
	lastline=''
	status=GetStatus(ID)
	sub=GetSubStatus(ID)
	if status==SST_LIST and sub==SST_LIST_ARTICLE:
		title=GetTitle(ID)
		#print 'send r'
		SendString(ID,'r')
		WaitFor(ID,bAutoEnter=False)
	elif status==SST_ARTICLE or status==SST_END or status==SST_ENTER:
		title=GetTitle(ID)
	else:
		return
	# now: SST_ARTICLE or SST_END or SST_ENTER
	while True:
		status=GetStatus(ID)
		if status==SST_ARTICLE:
			#print 'SST_ARTICLE'
			if savetype==0:
				data+=GetText(ID,0,22)
			else:
				data+=GetAttrText(ID,0,22)
			lastline=GetText(ID,22)
			SendString(ID,' ')
			WaitFor(ID,bAutoEnter=False)
		elif status==SST_END or status==SST_ENTER:
			#print status
			# 查找与上一屏的重复行；这也许可以用difflib来做
			start=0
			for i in range(22):
				s=GetText(ID,i)
				if s==lastline:
					start=i+1
					break
			if savetype==0:
				data+=GetText(ID,start,22)
			else:
				data+=GetAttrText(ID,start,22)
			SendString(ID,'q')
			break
		data+='\r\n'
	if savetype==2:
		data=HTMLHead(title)+AnsiToHTML(data)+HTMLEnd()
	return (title,data)

ansi2htmltable=[
('\x1b{1,2}\\[[\\d;]*[ABCDHIJKsumnphljyLMPRf@rgU]',''),
('&', "&amp;"),
(' ', "&nbsp;"),
('<', "&lt;"),
('>', "&gt;"),
('\"', "&quot;"),
]

# 颜色的处理比较麻烦

def AnsiToHTML(s):
	#print 'in AnsiToHTML'
	for index,repl in ansi2htmltable:
		s=re.sub(index,repl,s)
	s=re.sub('\n','<br>',s)
	return s

'''
	if(bFontChange)
			strcat(buf,"</font>");
		if(bBkColorChange)
			strcat(buf,"</span>");
		strcat(buf,"<br>\n");
'''	
def HTMLHead(title):
	return '''<HTML>
<HEAD><title>%s </title></HEAD>
<BODY bgcolor="#000000" link="#0099CC" text="#FFFFFF" vlink="#00CCCC" alink="#CCFF00">
<FONT FACE="宋体" LANG="ZH-CN" SIZE=3>\n'''%title

def HTMLEnd():
	return "</FONT></BODY>\n</HTML>"
