/*
XOWA: the XOWA Offline Wiki Application
Copyright (C) 2012 gnosygnu@gmail.com

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
package gplx.xowa; import gplx.*;
public class Xoi_mirror_parser {
	public String[] Parse(String raw_str) {
		if (String_.Len_eq_0(raw_str)) return String_.Ary_empty;
		byte[] raw = Bry_.new_utf8_(raw_str);
		ListAdp rv = ListAdp_.new_();
		int pos = 0;
		while (true) {
			int bgn = Bry_finder.Find_fwd(raw, CONST_href_bgn, pos); if (bgn == Bry_.NotFound) break;
			bgn += CONST_href_bgn.length;			
			int end = Bry_finder.Find_fwd(raw, CONST_href_end, bgn); if (end == Bry_.NotFound) return String_.Ary_empty;
			byte[] date = Bry_.Mid(raw, bgn, end); 
			pos = end + CONST_href_end.length;			
			if (Bry_.Match(date, CONST_date_parent_dir)) continue;
			int date_pos_last = date.length - 1;
			if (date_pos_last == -1) return String_.Ary_empty;
			if (date[date_pos_last] == Byte_ascii.Slash) date = Bry_.Mid(date, 0, date_pos_last);	// trim trailing /; EX: "20130101/" -> "20130101" 
			rv.Add(String_.new_utf8_(date));
		}
		return rv.XtoStrAry();
	}	static final byte[] CONST_href_bgn = Bry_.new_ascii_("<a href=\""), CONST_href_end = Bry_.new_ascii_("\""), CONST_date_parent_dir = Bry_.new_ascii_("../");
	public static String Find_last_lte(String[] ary, String comp) {	// assuming sorted ary, find last entry that is lte comp
		int len = ary.length;
		for (int i = len - 1; i > -1; i--) {
			String itm = ary[i];			
			if (CompareAble_.Is_lessOrSame(itm, comp)) return itm;
		}
		return "";
	}
}
