/*
 * 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 
//-----------------------------------------------------------------------------
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.io.BufferedReader;
import java.io.FileReader;
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
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.rz_VirtualVideoActionF;
import net.pms.dlna.virtual.VirtualFolder;
import net.pms.newgui.rz_WebTab;
import net.pms.configuration.PmsConfiguration;
import net.pms.configuration.RendererConfiguration;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class  rz_IavSelFolder extends VirtualFolder {
	private static final Logger logger = LoggerFactory.getLogger(rz_IavSelFolder.class);
	private boolean resolved;
	private PmsConfiguration conf = PMS.getConfiguration();
	private int clip_type;
	private long prevCallTime;
	private rz_IavSelFolder vf_del;
	private rz_IavSelFolder vf_sel;
	private ArrayList<DLNAResource> dellist= new ArrayList<DLNAResource>();
	private List<DLNAResource> chlist;
	private static String FSEP=File.separator;
	
	//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_IavSelFolder(String name,int clip_type, rz_IavSelCtl sc,RendererConfiguration r) {
		//rz_VirtualVideoActionF(String name, boolean enabled,int toggle_mode,int btn_type)
		super(name,null);
		//---- create me
		this.name=name;
		this.clip_type=clip_type;
		this.iavSelCtl=sc;
		this.setDefaultRenderer(r);
		this.vf_sel=this;
		this.sort_enabled=true;
		this.rz_MetaSortType=PMS.SORT_NAME_NUM;
		this.rz_MetaSortRecursive=true;
		resolve();
	}
	
	public boolean allowScan() {
		return true;  //for enable recursive sort, to be revised for the perpose
	}

	@Override
	public int activate(int type) {
		long tim1 = System.currentTimeMillis();
		if(type!=1 || (tim1-prevCallTime) <1000) { 
			return 0;
		}
		prevCallTime=tim1;
		
		if(clip_type==0 && dellist.size()>0) {
			chlist=getChildren(); 
			if(chlist!=null) {
				for(DLNAResource ch: dellist) {
					chlist.remove(ch);
				}
			}
			dellist.clear();
		}
		resolve();
		return 0;
	}

	@Override
	public synchronized void resolve() {
		if(clip_type==0) return;  //del buttons
		ArrayList<String> cpathlist;
		if(!resolved) {
			if(clip_type==1) {
				cpathlist=iavSelCtl.cpathlist_a;
			}
			else {
				cpathlist=iavSelCtl.cpathlist_v;
			}
			int ures=(isUnderResumeFolder(this)?1:0);// 
			createSortMenu(this,ures);
			
			createSelButtons(cpathlist,this);
			setLastmodified(System.currentTimeMillis()); //memory created time of me

			//public rz_IavSelFolder(String name,int clip_type, rz_IavSelCtl sc,RendererConfiguration r) {
			DLNAResource pa=getCtlFolder(true,ures);
			if(pa==null) pa=this;
				
			vf_del=new rz_IavSelFolder("#- Delete ClipPath -#",0,iavSelCtl,getDefaultRenderer());
			pa.addChildInternal(vf_del,0);
			//vf_del.sort_immune=1;
			createDelButtons(getChildren(),(DLNAResource)vf_del);
			vf_del.doSort=false;  //first, force order same as parent
		}
		resolved=true;
	}
	
	public void reset_enabled() {
		for(DLNAResource ch: getChildren()) {
			if(!(ch instanceof rz_VirtualVideoActionF)) continue;
			((rz_VirtualVideoActionF)ch).enabled=false;
			((rz_VirtualVideoActionF)ch).toString_sb=null;  //clear name cache
		}
	}
	
	public void set_cpath(String path) {
		iavSelCtl.set_cpath(clip_type,path);
	}
		
	public void sel_clip(int pos) {
		int i=0;
		rz_VirtualVideoActionF ch;
		for(DLNAResource d: getChildren()) {
			if(!(d instanceof rz_VirtualVideoActionF)) continue;
			ch=(rz_VirtualVideoActionF)d;
			if(pos==i) {
				ch.activate(1);
				break;
			}
			i++;
		}
	}
	
	public String add_clip(String name, String path) {
		//PMS.dbg("add_clip: name="+name+", path="+path+", to ClipFolder="+this);
		
		String errMsg=null;
		//---- duplicate check
		for(DLNAResource d: this.getChildren()) {
			if(d instanceof rz_VirtualVideoActionF) {
				String s=((rz_VirtualVideoActionF)d).getTargetPath();
				if(s.equals(path)) {
					//PMS.dbg("add_clip: already added, path="+path);
					errMsg="Updated(already exist), name="+name;
					//return -1;  //already exists
					return errMsg;  //already exists
				}
			}
		}
		
		//---- create select btn
		rz_VirtualVideoActionF btn=new rz_VirtualVideoActionF(name,false,1,0) {
			@Override
			public boolean enable() {
				rz_IavSelFolder pa=(rz_IavSelFolder)getParent();
				pa.reset_enabled(); //reset brothers
				pa.set_cpath(target_path);
				enabled=true;
				return (true);
			}
		};
		btn.setTargetPath(path);
		this.addChild(btn);
		
		/* following is more simple than above, but can't give name with path
		ArrayList<String>= plist=new ArrayList<>(path);
		createSelButtons(, (DLNAResource)this);
		*/
		
		//---- create delete btn
		//List<DLNAResource> clist=new ArrayList<>();
		//clist.add((DLNAResource)btn);
		if(vf_del==null) {
			vf_del=new rz_IavSelFolder("#- Delete ClipPath -#",0,iavSelCtl,getDefaultRenderer());
			addChildInternal(vf_del,0);
		}
		List<DLNAResource> clist=Arrays.asList((DLNAResource)btn);
		createDelButtons(clist, (DLNAResource)vf_del);
		doSort=true;
		vf_del.doSort=true;
		
		return null;
	}
	
	public void del_child(String target_path) {
		for(DLNAResource d: getChildren()) {
			if(d instanceof rz_VirtualVideoActionF) {
				if(((rz_VirtualVideoActionF)d).target_path.equals(target_path)) {
					//delete target dlna object
					getChildren().remove(d);
					
					//delete target file
					File f=new File(target_path);
					if(f.isFile()) {
						//PMS.dbg("rz_IavSelFolder.del_child: Delete RealClipFile="+f.getName()+" (Move to [clips/deleted] folder)");
						iavSelCtl.delClipFile(f);
					}
					
					return;
				}
			}
		}
	}
	
	public void del_child_delay(DLNAResource t) {
		dellist.add(t);
	}
	
	private void createSelButtons(ArrayList<String> pathlist, DLNAResource pa) {
		for(String str :pathlist) {
			File f=new File(str);
			String fname=null,sfx=null;
			if(!f.exists()) {
				iavSelCtl.recoverClipFile(f);
			}
			if(f.isFile()) {
				//PMS.dbg("createSelButtons: isFile()==true");
				try {
					LineNumberReader br = new LineNumberReader(new InputStreamReader(new FileInputStream(f)) );
					String line = null;
					int cnt=0;
					while ((line = br.readLine()) != null && cnt<3) {
						if(line.startsWith("#@name=")) {
							String str1=line.substring("#@name=".length()).trim();
							if(str1.startsWith("\"") && str1.endsWith("\"") && str1.length()>2) {
								str1=str1.substring(1,str1.length()-1);
							}
							if(str1.length()<=0) continue;
							fname=str1;
						}
						cnt++;
					} 
					br.close();
				} catch (IOException e){
					logger.error("createSelButtons: IOException: "+ e.getMessage());
				}
			}
			else {
				if(f.isAbsolute()) {
					if(!f.exists()) {
						sfx="(?)";  //not exists
					}
				}
			}
			//PMS.dbg("createSelButtons: fname="+fname);
			if(fname==null) {
				fname=f.getName();
				if(f.getParentFile()!=null) {
					fname=f.getParentFile().getName()+"/"+fname;
				}
			}
			if(sfx!=null) fname=fname+sfx;
			rz_VirtualVideoActionF btn=new rz_VirtualVideoActionF(fname,false,1,0) {
				@Override
				public boolean enable() {
					rz_IavSelFolder pa=(rz_IavSelFolder)getParent();
					pa.reset_enabled(); //reset brothers
					pa.set_cpath(target_path);
					enabled=true;
					return (true);
				}
			};
			btn.setTargetPath(str);
			pa.addChild(btn);
		}
	}

	private void createDelButtons(List<DLNAResource> clist, DLNAResource pa) {
		for(DLNAResource c : clist) {
			if(c instanceof rz_VirtualVideoActionF) {
				rz_VirtualVideoActionF d=(rz_VirtualVideoActionF)c;
				String fname="DEL - "+d.getBaseName();
				rz_VirtualVideoActionF btn=new rz_VirtualVideoActionF(fname,false,0,0) {
					@Override
					public boolean enable() {
						DLNAResource pa=getParent();
						vf_del.del_child_delay(this);  //delete me(btn) later
						vf_sel.del_child(target_path);
						enabled=true;
						return (true);
					}
				};
				btn.setTargetPath(d.getTargetPath());
				pa.addChild(btn);
			}
		}
	}


}
