/**
 * File:	modules/RichText.ycp
 * Package:	yast2
 * Summary:	Rich text manipulation routines
 * Authors:	Michal Svec <msvec@suse.cz>
 *		Stano Visnovsky <visnov@suse.cz>
 *
 * $Id: RichText.ycp 21259 2005-02-07 05:17:14Z nashif $
 */

{

module "RichText";
textdomain "base";
import "String";

define string DropWS(string text) ``{
    list<string> filteredlist = splitstring(text, "\n	");
    return String::CutBlanks(mergestring(filteredlist, " "));
}

/**
 * Convert a richtext string into a formatted plain text.
 * @param richtext the text to be converted
 * @return the converted text
 */
global define string Rich2Plain (string richtext) ``{
    y2debug("richtext=%1", richtext);

    list<string> lparts = splitstring(DropWS(richtext), "<");
    y2debug("lparts=%1", lparts);

    /* Am I in <LI>? */
    boolean inli = false;

    /* Indentation level */
    integer indents = 0;

    string result = "";
    foreach (string lpart, lparts, ``{
	integer s = find( lpart, ">" );
	string tag = tolower(substring( lpart, 0, s ));

	/**** Handle tags *****/

	/* BR */
	if( tag == "br" ) {
	    result = result + "\n";
	}
	/* P */
	else if( tag == "p" ) {
	    result = result + "\n";
	}
	/* UL */
	else if( tag == "ul" ) {
	    inli = true;
	    indents = indents + 1;
	}
	/* /UL */
	else if( tag == "/ul" ) {
	    if(inli && indents == 1) result = result + "\n";
	    indents = indents - 1;
	    inli = false;
	}
	/* LI */
	else if( tag == "li" ) {
	    if(inli) result = result + "\n";
	    inli = true;
	}
	/* /LI */
	else if( tag == "/li" ) {
	    inli = false;
	    result = result + "\n";
	}

	/**** Add the text *****/

	if(s != -1) lpart = String::CutBlanks(substring(lpart, s+1));
	if(regexpmatch(lpart, "^[ \n	]*$")) return;
	if(lpart == "&nbsp;") return;

	if(lpart != "" && inli) {
	    integer i = 1;
	    while(i < indents) {
		result = result + "  ";
		i = i + 1;
	    }
	    lpart = "* " + lpart;
	}
	// result = result + "[" + lpart + "]";
	result = result + lpart;
    });
    result = String::CutBlanks(result);
    if((size(result) > 0) && (substring(result, size(result)-1) != "\n"))
	result = result + "\n";

    y2debug(result);
    return result;
}

/**
 * Parse provided text and see if it contains richtext
 * @param file file path
 * @return symbol
 */
global symbol DetectRichText(string file )
{
    string text = "";

    if (SCR::Read(.target.size, file) > 0)
    {
        text = (string)SCR::Read(.target.string,  file );
    }
    else 
    {
        return `error;
    }

    if (text == "")
    {
        return `empty;
    }

    if (regexpmatch(text, "</.*>")) {
        return `richtext;
    } else {
        return `plaintext;
    }
}

/* EOF */
}
