package org.zhios.website.admin.pagelet;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Comparator;

import org.w3c.dom.Document;
import org.zhios.website.admin.model.ConfFileOpt;
import org.zhios.website.admin.model.HtmlOpt;
import org.zhios.website.admin.model.Strings;
import org.zhios.website.admin.model.SysConfig;

public class NewsListPL extends BasePageLet implements PageLetObj {

	public NewsListPL(String divid) {
		super(divid);
		// TODO Auto-generated constructor stub
	}
	
	public NewsListPL(String divid, String okfunc, String cancelfunc, String outerhtml) {
		super(divid,okfunc,cancelfunc,outerhtml);
		// TODO Auto-generated constructor stub
	}

	protected void setFill(String type, String descriptor, String name, String oldvalue, String initstring, boolean noempty){
		String required="";
		if(noempty){
			descriptor="*"+descriptor;
			required=" required";
		}
		
		if(type.equals("packagelist")){
			ConfFileOpt packageconf=new ConfFileOpt(SysConfig.RootPath+"/package/package.xml");
			String[][] packages=packageconf.getNodesIdName("package");

			FillStr+="<tr><td width='100px' align='right'>"+descriptor+"</td><td>"+
					"<select style='width:250px' name='"+name+"'"+required+"><option value=''></option>";
			for(int i=0;i<packages.length;i++){
				String packageid=packages[i][0];
				String packagename=packages[i][1];
				if(packageid.equals(oldvalue))
					FillStr+="<option value='"+packageid+"' selected>"+packagename+"</option>";
				else
					FillStr+="<option value='"+packageid+"'>"+packagename+"</option>";
			}
			FillStr+="</select></td></tr>";
		}
		else super.setFill(type, descriptor, name, oldvalue, initstring, noempty);
	}
	
	public void setFillStr(){
		//Get previous value of every fills.
		String width="",height="",bgimage="",divfloat="",packagename="";
		if(!OuterStr.isEmpty()){
			divfloat=HtmlOpt.readFirstTagStyleAttrValue(OuterStr,"div","float");
			if(divfloat.isEmpty()) divfloat="center";
			
			width=HtmlOpt.readFirstTagStyleAttrValue(OuterStr,"div","width");
			if(!width.isEmpty()){
				int px=width.indexOf("px");
				if(px>0) width=width.substring(0,px);
			}
			
			height=HtmlOpt.readFirstTagStyleAttrValue(OuterStr,"div","height");
			if(!height.isEmpty()){
				int px=height.indexOf("px");
				if(px>0) height=height.substring(0,px);
			}
			
			bgimage=HtmlOpt.readFirstTagStyleAttrValue(OuterStr,"div","background-image");
			if(!bgimage.isEmpty()){
				bgimage=bgimage.substring(bgimage.indexOf("/userimage/")+"/userimage/".length(),bgimage.indexOf(")"));
			}

			packagename=HtmlOpt.readFirstTagStyleAttrValue(OuterStr,"div","tmpackage");
		}
		
		//Set every fills.
		setFill("text",Strings.PLWidth,"width",width,"",true);
		setFill("text",Strings.PLHeight,"height",height,"",true);
		setFill("select",Strings.PLFloat,"float",divfloat,"left,center,right",true);
		setFill("packagelist",Strings.PLPackageList,"packagelist",packagename,"",true);
		setFill("image",Strings.PLBGImage,"bgimage",bgimage,"",false);
	}

	public void setViewStr(Document doc){
		String divfloat=doc.getElementsByTagName("float").item(0).getTextContent();
		String floatstr;
		if(divfloat.equals("center")) floatstr="margin:auto";
		else floatstr="float:"+divfloat;
		String width=doc.getElementsByTagName("width").item(0).getTextContent();
		String height=doc.getElementsByTagName("height").item(0).getTextContent();
		String bgimage=SysConfig.ResourceUrl+"/userimage/"+doc.getElementsByTagName("bgimage").item(0).getTextContent();
		
		String packagename=doc.getElementsByTagName("packagelist").item(0).getTextContent();
		String packagepath=SysConfig.RootPath+"/package/"+packagename;
		File packagefloder=new File(packagepath);
		
		String allfilename[]=packagefloder.list();
		Comparator<String> mycon=new RevStrComp();
		Arrays.sort(allfilename,mycon);
				
		ViewStr="<div id='"+DivID+"' tmstyle='newslist' style='tmpackage:"+packagename+";"+floatstr+";width:"+width+"px;height:"+height+"px;background-image:url("+bgimage+");background-repeat:no-repeat'>";
		ViewStr+="<table width='100%'>";
		
		int newsmaxcount=Integer.parseInt(height)/25;
		int newsmaxtitle=(Integer.parseInt(width)-85)/14;
		int newscount=allfilename.length;
		newscount=(newscount<newsmaxcount)?newscount:newsmaxcount;
		String temptitle;
		for(int i=0;i<newscount;i++){
			temptitle=GetFileTitle(packagepath+"/"+allfilename[i]);
			if(temptitle.length()>newsmaxtitle&&newsmaxtitle>2)
				temptitle=temptitle.substring(0,newsmaxtitle-2)+"...";
			if(!temptitle.isEmpty())
				ViewStr+="<tr><td height='25px' style='padding-left:10px;'><a href='"+SysConfig.RootUrl+"/package/"+packagename+"/"+allfilename[i]+"' target='_blank'>"+temptitle+"</a></td>" +
						"<td width='65px' align='right' style='padding-right:10px;'>("+allfilename[i].substring(0,8)+")</td></tr>";
		}
		
		ViewStr+="</table></div>";
		
	}
	
	public String resetViewStr(String outerhtml){
		OuterStr=outerhtml;
		
		//Get previous value of every fills.
		String width="",height="",bgimage="",floatstr="",packagename="";
		if(outerhtml.isEmpty()) return "";
		
		floatstr=HtmlOpt.readFirstTagStyleAttrValue(OuterStr,"div","float");
		if(floatstr.isEmpty()) floatstr="margin:auto";
		else floatstr="float:"+floatstr;
		
		width=HtmlOpt.readFirstTagStyleAttrValue(OuterStr,"div","width");
		
		height=HtmlOpt.readFirstTagStyleAttrValue(OuterStr,"div","height");
		
		bgimage=HtmlOpt.readFirstTagStyleAttrValue(OuterStr,"div","background-image");

		packagename=HtmlOpt.readFirstTagStyleAttrValue(OuterStr,"div","tmpackage");
		String packagepath=SysConfig.RootPath+"/package/"+packagename;
		File packagefloder=new File(packagepath);
		
		String allfilename[]=packagefloder.list();
		Comparator<String> mycon=new RevStrComp();
		Arrays.sort(allfilename,mycon);
		
		String result="<div id='"+DivID+"' tmstyle='newslist' style='tmpackage:"+packagename+";"+floatstr+";width:"+width+";height:"+height+";background-image:"+bgimage+";background-repeat:no-repeat'>";
		result+="<table width='100%'>";
		
		int newsmaxcount=Integer.parseInt((height.indexOf("px")>=0)?height.substring(0, height.indexOf("px")):height)/25;
		int newsmaxtitle=(Integer.parseInt((width.indexOf("px")>=0)?width.substring(0, width.indexOf("px")):width)-85)/14;
		int newscount=allfilename.length;
		newscount=(newscount<newsmaxcount)?newscount:newsmaxcount;
		String temptitle;
		for(int i=0;i<newscount;i++){
			temptitle=GetFileTitle(packagepath+"/"+allfilename[i]);
			if(temptitle.length()>newsmaxtitle&&newsmaxtitle>2)
				temptitle=temptitle.substring(0,newsmaxtitle-2)+"...";
			if(!temptitle.isEmpty())
				result+="<tr><td height='25px' style='padding-left:10px;'><a href='"+SysConfig.RootUrl+"/package/"+packagename+"/"+allfilename[i]+"' target='_blank'>"+temptitle+"</a></td>" +
						"<td width='65px' align='right' style='padding-right:10px;'>("+allfilename[i].substring(0,8)+")</td></tr>";
		}
		
		result+="</table></div>";
		
		return result;
	}

	private String GetFileTitle(String filepath){
		if(filepath==null) return null;

	    String titlestr="";
		try {
			File file=new File(filepath);
			if(file.exists()){
			    InputStreamReader ireader = new InputStreamReader(new FileInputStream(file),"UTF-8"); 
			    BufferedReader buffreader=new BufferedReader(ireader);
			    
			    int tempstart=0,tempend=0;
			    while((titlestr=buffreader.readLine())!=null){if((tempstart=titlestr.indexOf("<title>"))>=0) break;}
			    
			    if(!titlestr.isEmpty()){
				    tempstart+=7;
				    tempend=titlestr.indexOf("</title>");
				    if(tempend>=0) titlestr=titlestr.substring(tempstart,tempend);
				    else titlestr=titlestr.substring(tempstart);
			    }
			    
			    buffreader.close();
			    ireader.close();
			}
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		
		return titlestr;
	}
	
	class RevStrComp implements Comparator<String> {
		public int compare(String strA, String strB) {
			return strB.compareTo(strA);
		}
	}
}
