# coding=utf-8

import json;
import sys;
import os;
from bs4 import BeautifulSoup


# 从命令行读取参数
# channelId = sys.argv[1]

def readFile(fname):
	file_object = open(fname, 'r')
	return file_object.read()
	
def writeFile(content , fname):
	file_object = open(fname  , 'w')
	return file_object.write(content)
	
def setCoding():
	reload(sys)
	sys.setdefaultencoding('utf-8')
	
def html2Soup(content):
	soup = BeautifulSoup(content,"lxml")
	return soup
	
def delGuijing(soup):
	i = 0 
	for sectionTag in soup.find_all("section"):
		if i == 3 :
			sectionTag.extract()
		i = i + 1

	return soup

def delAllAlink(soup):
	for aTag in soup.find_all("a"):
		if aTag.string != None:
			aTag.insert_after(aTag.string)
		aTag.extract()
	return soup
	
def getIconUrl(soup , index):
	icon = soup.img['src'].replace("!lw-720" , "!lw-240")
	
	soup.img['src'] = "http://cdn.sinacloud.net/cmssp-image-1/"+str(index)+".jpg";
	
	return icon
	
	
if __name__ == '__main__':


	updateSQL = "update cmssp_drug set icon='{icon}' where id = {id};"

	setCoding()
	
	jsoncontent = json.loads(readFile("drug.json"))
	
	htmlContent = readFile("template.html")
	
	sqls = ""
	
	i = 0
	for json in jsoncontent:
		i = i + 1
		print "create html index :" + str(i) +"\n"
		tempHtml = htmlContent.replace("{title}" , json['name'])\
		.replace("{content}" , json['summary'])
		
		soup = html2Soup(tempHtml)
		
		delGuijing(soup)
		
		delAllAlink(soup)
		
		icon = getIconUrl(soup , i)
		
		tempSQL = updateSQL.replace("{icon}" , icon).replace("{id}" , str(i))
		
		sqls = sqls + tempSQL + "\n"
		
		writeFile(str(soup) , str(i)+".html")

	writeFile(sqls , "updateSQLS")

		