/*
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; version 2
 * of the License only.
 *
 * 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */
//-----------------------------------------------------------------------------
// Regzamod specific class
// Manage Special WebFolder/Entries for Quick play with inputted URL from UI
//-----------------------------------------------------------------------------
package net.pms.dlna;

import java.io.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.StringTokenizer;
import java.util.Calendar;

import net.pms.PMS;
import net.pms.formats.Format;
import net.pms.util.FileUtil;
import net.pms.util.ProcessUtil;
import net.pms.util.PMSUtil;
import net.pms.dlna.DLNAResource;
import net.pms.dlna.virtual.VirtualFolder;
import net.pms.newgui.rz_WebTab;
import net.pms.dlna.rz_KeywordMenu;
import net.pms.dlna.virtual.VirtualVideoAction;
import net.pms.configuration.PmsConfiguration;

import org.apache.commons.lang.StringUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class  rz_WebQSFolder extends DLNAResource {
	private static final Logger logger = LoggerFactory.getLogger(rz_PlayMetaFile.class);
	private DLNAResource parent_top;
	private String myname;
	private VirtualFolder myfolder;
	private rz_KeywordMenu kwmBase;
	private long prevCallTime=0;
	private boolean resolved;
	private PmsConfiguration configuration = PMS.getConfiguration();
	private ArrayList<DLNAResource> palist = new ArrayList<DLNAResource>();	//leaf parent list

	//subclass constructor must exec super's constructor
	//if you don't explicitly call super(params)
	//then subclass constructor implicitly call super's constructor with "no param"
	
	public rz_WebQSFolder(DLNAResource parent,String name,int btn_type) {
		//---- create me
		myname=name;
		sort_enabled=true;
		rz_MetaSortType=PMS.SORT_ORIGIN;
		
		//---- load keyword menues
		// Children(roots for per kwdlist) are created by rz_KeywordMenu, instead of by resolve()
		String kwdmenu_conf=configuration.getRZ_kwdmenu_conf();
		List<String> kwdlist_conf_paths=configuration.getRZ_kwdlist_confPaths();
		kwmBase= new rz_KeywordMenu(this,kwdmenu_conf,kwdlist_conf_paths,btn_type);
		
		setLastmodified(System.currentTimeMillis()); 
	}
	
	public rz_KeywordMenu getKeywordMenu() {
		return kwmBase;
	}
	
	@Override
	public int activate(int type) {
		long tim1 = System.currentTimeMillis();
		if(type!=1 || (tim1-prevCallTime) <1000) { 
			return 0;
		}
		prevCallTime=tim1;
		resolve();
		return 0;
	}
	
	//return true, if the container is changed, so refresh is needed
	@Override
	public boolean isRefreshNeeded() {
		long t1=getLastmodified();
		long t2=PMS.dt_modified_time;
		//PMS.dbg("rz_WebQSFolder.isRefreshNeeded: getLastmodified="+t1+", PMS.dt_modified_time="+t2);
		if(t1<t2) {
			//PMS.dbg("rz_WebQSFolder.isRefreshNeeded: t1<t2 return true");
			return true;
		}
		//PMS.dbg("rz_WebQSFolder.isRefreshNeeded: t1>=t2 return false");
		return false;
	}
	
	@Override
	public void refreshChildren() {
		//PMS.dbg("rz_WebQSFolder.refreshChildren: called");
		resolved=false;
		resolve();
	}

	
	@Override
	public boolean  needSort() {	//regzamod
		//children(play list) shouldn't be sorted !!
		return false;
	}
	
	@Override
	public InputStream getInputStream() throws IOException {
		return null;
	}

	public String getName() {
		return myname;
	}
	public String getName0() {
		return myname;
	}
	@Override
	public String getDpName() {	//regzamod
		return getName();
	}

	@Override
	public String getSystemName() {
		return myname;
	}

	@Override
	public boolean isFolder() {
		return true;
	}

	@Override
	public boolean isValid() {
		return true;
	}

	@Override
	public long length() {
		return 0;
	}
	
	@Override
	public synchronized void resolve() {
		long t1=getLastmodified();
		long t2=PMS.dt_modified_time;
		
		//PMS.dbg("rz_WebQSFolder.resolve: getLastmodified="+t1+", PMS.dt_modified_time="+t2);
		if(t1<t2) {
			//PMS.dbg("rz_WebQSFolder.resolve: t1<t2, updated --> exec resolve");
			resolved=false;
		}
		else {
			//PMS.dbg("rz_WebQSFolder.resolve: t1>=t2, not updated --> Noop");
		}

		if(!resolved) {
			del_children();
			add_children(this);
			setLastmodified(System.currentTimeMillis()); //memory created time of me
		}
		resolved=true;
	}
	
	private void del_children() {
		DLNAResource ch;
		int size=palist.size();
		for(int i=0;i<size;i++) {
			ch=palist.get(i);
			if(ch!=null) {
				getChildren().remove(ch);
			}
		}
	}
	
	//---- create folder/entries
	private void add_children(DLNAResource parent) {
		DLNAResource obj,vf,pa;
		String stype,name,subname,url,param;
		ArrayList<String[]> sites= new ArrayList<String[]>();
		sites.addAll(PMS.get().getRzw().sc_defaults);
		sites.addAll(PMS.get().getRzw().ch_defaults);
		sites.addAll(PMS.get().getRzw().st_defaults);
		
		int sc_cnt=PMS.get().getRzw().sc_defaults.size();
		int ch_cnt=sc_cnt+PMS.get().getRzw().ch_defaults.size();
		
		String sch_str=kwmBase.dt_sc_str.substring(0).trim();
		String sch_str0=sch_str;  //memory original
		//sch_str=sch_str.replaceAll(" ","+");
		sch_str=DLNAResource.encode(sch_str);  //encode for HTML representation
		
		//---- Child folder for search
		int i=0;
		int sc_size=PMS.get().getRzw().sc_defaults.size();
		for(String[] val: sites) {
			//val[]={type},{path},{name},{base_url},{search_string},{options}
			i++;
			obj=null;
			if(val.length<4) continue;
			stype=val[0].trim();
			name=val[2].trim(); 
			subname=null;
			if(i<=sc_cnt) {
				if(sch_str.length()<=0) {
					url=null;
				}
				else if(val.length>=6) {
					//url=val[3].trim()+ PMS.dt_sc_str.trim() + val[5].trim();
					url=val[3].trim()+ sch_str + val[5].trim();
				}
				else {
					//url=val[3].trim()+ PMS.dt_sc_str.trim();
					url=val[3].trim()+ sch_str;
				}
				subname=sch_str0;
				//PMS.dbg("rz_WebQSFolder.add_children: search url="+url);
			}
			else if(i<=ch_cnt) {
				if(sch_str.length()<=0) {
					if(val.length>=5) sch_str=val[4].trim();
					else sch_str=PMS.dt_ch_str;
					if(sch_str==null) sch_str="";
				}
				if(val.length>=6) 
					url=val[3].trim()+ sch_str + val[5].trim();
				else 
					url=val[3].trim()+ sch_str;
				//PMS.dbg("rz_WebQSFolder.add_children: channel url="+url);
			}
			else {
				url=val[3].trim();
			}
			vf=PMSUtil.createDLNApath(parent,val[1].trim(),"/");
			if(stype.equals("videofeed")) {
				obj=new VideosFeed(url,name);
			}
			else if(stype.equals("imagefeed")) {
				obj=new ImagesFeed(url,name);
			} else if (stype.equals("audiofeed")) {
				obj=new AudiosFeed(url,null);
			} else if (stype.equals("audiostream")) {
				obj=new WebAudioStream(name, url, null);
			} else if (stype.equals("videostream")) {
				obj=new WebVideoStream(name, url, null);
				//PMS.dbg("WebVideoStream: name="+name+", url="+url);
			}
			if(obj!=null) {
				if(subname!=null) {
					obj.setSubName(subname);
				}
				obj.mflags |= DLNAResource.MF_WEB_FOLDER;
				obj.mflags |= DLNAResource.MF_WEB_RESUME_FOLDER;
				
				//vf.addChildInternal(obj);
				vf.addChild(obj);
				pa=PMSUtil.getDirectChild(parent,vf);
				if(pa!=null) {
					pa.setSerialId(i+10);  //make after rz_KeywordMenu in list
					palist.add(pa);
				}
			}
		}
		//---- Child folder for stream
	}
	
	
	
	/**
	 * Splits the first part of a WEB.conf spec into a pair of Strings
	 * representing the resource type and its DLNA folder.
	 * @param spec
	 *            (String) to be split
	 * @return Array of (String) that represents the tokenized entry.
	 */
	private String[] parseFeedKey(String spec) {
		String[] pair = StringUtils.split(spec, ".", 2);

		if (pair == null || pair.length < 2) {
			pair = new String[2];
		}
		if (pair[0] == null) {
			pair[0] = "";
		}
		return pair;
	}
	
	/*
	static class dpkwd extends VirtualFolder {
		String name;
		public dpkwd(String name) {
			super(name,null);  //should call, if params not equals to super constructor
			this.name    = name;
			VirtualVideoAction va=new VirtualVideoAction("OK", true) {
				@Override public boolean enable() {return true;}
			};
			addChild(va);
		}
		
		@Override
		public String getName () {
			return name+" [ "+kwmBase.dt_sc_str+" ]";
		}
	}
	*/

}
