package com.sabirjan.liulanqi.Wangluo;

import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Attribute;
import org.jsoup.nodes.Attributes;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.nodes.TextNode;
import org.jsoup.parser.Tag;

import com.sabirjan.liulanqi.Mytest.ConvertUL;

public class html {

    static ConvertUL cls=new ConvertUL();
	public static String get(String content,int len)
	{
		Document dirtyDocument=Jsoup.parse(content);
		
		Element source=dirtyDocument.body();
		Document clean=Document.createShell(dirtyDocument.baseUri());
		
		Element dest=clean.body();
		
		trunCreateHTML(source,dest,len);
		return dest.outerHtml();
	}
	public static void trunCreateHTML(Element source,Element dest,int len)
	{
		List<Node> sourceChildren=source.childNodes();
		
		for(Node sourceChild:sourceChildren)
		{
			if(sourceChild instanceof Element)
			{
				Element sourceEl=(Element)sourceChild;
				Element destChild=createSafeElment(sourceEl);
				System.out.println("HHHHHHH:"+dest.text());
				int txt=dest.text().length();
			
				if(txt>=len)
				{
					break;
				}
				else
				{
					len=len-txt;
					
				}
				dest.appendChild(destChild);
				trunCreateHTML(sourceEl,destChild,len);
			}
			else if(sourceChild instanceof TextNode)
			{
				int destLeng=dest.text().length();
				if(destLeng>=len)
				{
					break;
				}
				TextNode sourceText=(TextNode)sourceChild;
				int txtLeng=sourceText.getWholeText().length();
				System.out.println("Dest:"+sourceText.getWholeText());
				if((destLeng+txtLeng)>len)
				{
					int tmp=len-destLeng;
					String txt=sourceText.getWholeText().substring(0,tmp);
					txt=cls.GetULUyghurWord(txt);
					TextNode destText=new TextNode(txt,sourceChild.baseUri());
					dest.appendChild(destText);
					break;
				}
				else
				{
					String txt=sourceText.getWholeText();
					txt=cls.GetULUyghurWord(txt);
					TextNode destText=new TextNode(txt,sourceChild.baseUri());
					dest.appendChild(destText);
				}
				
			}
			}
		}
			private static Element createSafeElment(Element sourceEl)
			{
				String sourceTag=sourceEl.tagName();
				Attributes destAttrs=new Attributes();
				Element dest=new Element(Tag.valueOf(sourceTag),sourceEl.baseUri(),destAttrs);
				Attributes sourceAttrs=sourceEl.attributes();
				for(Attribute sourceAttr:sourceAttrs)
				{
					destAttrs.put(sourceAttr);
				}
				System.out.println("sourceText.getWholeText():"+dest.text());
				return dest;
				
				}
}
