/*
 * PS3 Media Server, for streaming any medias to your PS3.
 * Copyright (C) 2008  A.Brochard
 *
 * 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.
 */
package net.pms.dlna;

import java.io.IOException;
import java.io.InputStream;

import net.pms.PMS;
import net.pms.configuration.PmsConfiguration;
import net.pms.dlna.DLNAResource;
import net.pms.dlna.virtual.VirtualFolder;
import net.pms.dlna.virtual.VirtualVideoAction;
import net.pms.dlna.rz_KwdGroup;
//import net.pms.dlna.rz_KeywordMenu;

import net.pms.network.HTTPResource;

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

/**
 * Implements a container that when browsed, an action will be performed.
 * The class assumes that the action to be performed is to toggle a boolean value.
 * Because of this, the thumbnail is either a green tick mark or a red cross. Equivalent
 * videos are shown after the value is toggled.<p> 
 * However this is just cosmetic. Any action can be performed.
 */
 
//------------------------------------------------
// Change type of Buttons from File to Folder:
// that protects miss(unwanted)-selection of the Buttons by moving cursols
// B/C Folder type buttons only activated by Open the folder intendedly
// and not opened by moving cursols
//------------------------------------------------
//public class rz_KeywordMenuBtn extends VirtualFolder {
public class rz_KeywordMenuBtn extends rz_VirtualVideoActionF {
	private static final Logger logger = LoggerFactory.getLogger(rz_KeywordMenuBtn.class);
	private String thumbnailIconOK;
	private String thumbnailIconKO;
	private String thumbnailContentType;
	private String videoOk;
	private String videoKo;
	private long timer1;
	private long prevCallTime=0;
	
	private boolean enabled;
	private int mode; //action mode =0:toggleButton, =1:pushButton
	protected String name;
	protected String[] cmd;
	private boolean dpinput;
	private boolean dplist_def;
	private boolean dplist_cur;
	public rz_KeywordMenu menuRoot;
	private rz_VirtualVideoActionF vab;
	public rz_KwdGroup kwg;
	private boolean gotChild;
	
	/**Constructor for this class. Recommended instantation includes overriding the {@link #enable()} function (example shown in the link).
	 * @param name Name that is shown via the UPNP ContentBrowser service. This field cannot be changed after the instantiation.
	 * @param enabled If true, a green tick mark is shown as thumbnail. If false, a red cross is shown. This initial value
	 * is usually changed via the {@link #enable()} function.
	 */
	public rz_KeywordMenuBtn(String name,rz_KeywordMenu menuRoot) {
		//super(name,null);  //should call, if params not equals to super constructor
		super(name,false,0,menuRoot.btn_type);  //should call, if params not equals to super constructor
		this.menuRoot=menuRoot;
		this.rz_MetaSortType=PMS.SORT_ORIGIN;  //sort by id: order of created
		construct(name,null,0,false);
		if(menuRoot==null) {
			logger.error("rz_KeywordMenuBtn: menuRoot==null name="+name);
		}
	}
	
	public rz_KeywordMenuBtn(String name,String[] cmd,int mode, boolean dpinput,rz_KeywordMenu menuRoot) {
		//super(name,null);  //should call, if params not equals to super constructor
		super(name,false,0,menuRoot.btn_type);  //should call, if params not equals to super constructor
		this.menuRoot=menuRoot;
		construct(name,cmd,mode,dpinput);
		if(menuRoot==null) {
			logger.error("rz_KeywordMenuBtn: menuRoot==null name="+name);
		}
	}
	
	private void construct(String name, String[] cmd, int mode, boolean dpinput) {
		this.name    = name;
		this.cmd = cmd;
		this.mode = mode;
		this.dpinput = dpinput;
		
		/*
		vab=new VirtualVideoAction("OK", true) {
			@Override public boolean enable() {return true;}
		};
		addChild(vab);
		*/
		
		if(cmd==null) return;
		for(String s : cmd) {
			if(s.equals("cmd_dsp")) {
				this.dpinput=true;
			}
			if(s.equals("cmd_dplist_def")) {
				this.dplist_def=true;
			}
			else if(s.equals("cmd_dplist_cur")) {
				this.dplist_cur=true;
			}
		}
	}
	
	public void setMenuRoot(rz_KeywordMenu obj) {
		menuRoot=obj;
	}
	
	@Override
	public int activate(int type) {
		long tim1 = System.currentTimeMillis();
		
		if(PMS.rz_debug>1) PMS.dbg("rz_KeywordMenuBtn.activate: called");
		if(type!=1 || (tim1-prevCallTime) <1000) { 
			// type=1: indicate Folder Open action from renderer, called 2 times on one open why??
			if(PMS.rz_debug>1) PMS.dbg("rz_KeywordMenuBtn.activate: called, in short time, ignore");
			return 0;
		}
		prevCallTime=tim1;
		String kwd=menuRoot.dt_sc_str;
		if(menuRoot==null) {
			logger.error("KewordMenuBtn.activate: menuRoot==null, Something wrong!");
			return 0;
		}
		menuRoot.resetErrMsg();
		//PMS.dbg("kwd input/select: kwg gname="+kwg.gname+",input_mode="+kwg.input_mode);

		if(mode==0) {
			// set keyword
			if(kwg.input_mode==rz_KwdGroup.IPMD_APPEND) {
				//PMS.dbg("IPMD_APPEND");
				menuRoot.dt_sc_str +=this.name;
			}
			else if(kwg.input_mode==rz_KwdGroup.IPMD_APPEND_PLUS) {
				//PMS.dbg("IPMD_APPEND_PLUS");
				if(menuRoot.dt_sc_str.length()>0)
					menuRoot.dt_sc_str +="+"+this.name;
				else 
					menuRoot.dt_sc_str =this.name;
			}
			else if(kwg.input_mode==rz_KwdGroup.IPMD_OVERWRITE) {
				//PMS.dbg("IPMD_OVERWRITE");
				menuRoot.dt_sc_str =this.name;
			}
			else { //rz_KwdGroup.IPMD_OVERWRITE
				//PMS.dbg("Unknown");
				menuRoot.dt_sc_str =this.name;
			}
			menuRoot.undo_put(menuRoot.dt_sc_str);
		}
		else if(mode==1 && cmd!=null && cmd.length>1) {
			//---- an easy way : to be refined
			if(cmd[1].equals("cmd_undo")) {
				menuRoot.dt_sc_str = menuRoot.undo_get();
			}
			else if(cmd[1].equals("cmd_redo")) {
				menuRoot.dt_sc_str = menuRoot.redo_get();
			}
			else {
				if(cmd[1].equals("cmd_clear")) {
					menuRoot.dt_sc_str ="";
					menuRoot.undo_put(menuRoot.dt_sc_str);
				}
				else if(cmd[1].equals("cmd_bs")) {
					int cnt=1;
					if(cmd.length>2) cnt=Integer.parseInt(cmd[2].trim());
					int len=menuRoot.dt_sc_str.length();
					if(len>=cnt){
						menuRoot.dt_sc_str = menuRoot.dt_sc_str.substring(0,len-cnt);
						menuRoot.undo_put(menuRoot.dt_sc_str);
					}
				}
				else if(cmd[1].equals("cmd_del")) {
					int cnt=1;
					if(cmd.length>2) cnt=Integer.parseInt(cmd[2].trim());
					//int len=menuRoot.dt_sc_str.length();
					int len=menuRoot.dt_sc_str.length();
					if(len>=cnt){
						//menuRoot.dt_sc_str = menuRoot.dt_sc_str.substring(cnt);
						menuRoot.dt_sc_str = menuRoot.dt_sc_str.substring(cnt);
						menuRoot.undo_put(menuRoot.dt_sc_str);
					}
				}
				//---- on default list
				else if(cmd[1].equals("cmd_addlist_def")) {
					menuRoot.addKeyword(kwd,null,0);
				}
				else if(cmd[1].equals("cmd_movlist_def")) {
					menuRoot.addKeyword(kwd,null,0);
					if(menuRoot.chkErrMsg()==null) {
						menuRoot.delKeyword(kwd,null,1);
					}
				}
				//---- on current list
				else if(cmd[1].equals("cmd_setlist_def")) {
					menuRoot.setCurToDefList();
				}
				else if(cmd[1].equals("cmd_addlist_cur")) {
					menuRoot.addKeyword(kwd,null,1);
				}
				else if(cmd[1].equals("cmd_dellist_cur")) {
					menuRoot.delKeyword(kwd,null,1);
				}
				//---- file
				else if(cmd[1].equals("cmd_save")) {
					//PMS.dbg("cmd_save: cmd.length="+cmd.length);
					if(cmd.length>2) {
						int mode=Integer.parseInt(cmd[2].trim());
						//PMS.dbg("cmd_save: cmd[2]="+cmd[2].trim()+", mode="+mode);
						menuRoot.saveKeywordList(mode);
					}
					else {
						menuRoot.saveKeywordList(0);
					}
				}
				else if(cmd[1].equals("cmd_load")) {
					if(PMS.rz_debug>1) PMS.dbg("rz_KeywordMenuBtn: cmd_load: exec menuRoot.reloadKeywordList()");
					//menuRoot.reloadKeywordList();
					menuRoot.kwdlist_need_update=true;  //don't work well
				}
				//---- input mode
				else if(cmd[1].equals("cmd_ipmd_ovw")) {
					kwg.input_mode=rz_KwdGroup.IPMD_OVERWRITE;
					//PMS.dbg("cmd_ipmd_ovw: kwg.gname="+kwg.gname+", IPMD_OVERWRITE");
				}
				else if(cmd[1].equals("cmd_ipmd_app")) {
					kwg.input_mode=rz_KwdGroup.IPMD_APPEND;
					//PMS.dbg("cmd_ipmd_app: kwg.gname="+kwg.gname+", IPMD_APPEND");
				}
				else if(cmd[1].equals("cmd_ipmd_app_plus")) {
					kwg.input_mode=rz_KwdGroup.IPMD_APPEND_PLUS;
					//PMS.dbg("cmd_ipmd_app_plus: kwg.gname="+kwg.gname+", IPMD_APPEND_PLUS");
				}
			}
		}
		String err_str=menuRoot.getErrMsg();
		if(!gotChild) {
			if(getChildren()!=null && getChildren().size()>=1) {
				vab=(rz_VirtualVideoActionF)(getChildren().get(0));
			}
			gotChild=true;
		}
		if(vab!=null) {
			if(err_str!=null) {
				vab.setName(err_str);
			}
			else {
				vab.setName("OK");
			}
		}
		PMS.dt_modified_time=System.currentTimeMillis();
		//PMS.dbg("rz_KeywordMenuBtn: keyword selected="+kwd+", current-input="+menuRoot.dt_sc_str);
		return 0;
	}
	
	@Override
	public String getName () {
		String nm;
		
		if(PMS.rz_debug>1) PMS.dbg("KeywordMenuBtn.getName: name="+name
			+", dpinput="+dpinput
			+", menuRoot.dt_sc_str="+menuRoot.dt_sc_str);
		
		if(dpinput) {  //disp input field
			if(menuRoot==null) {
				//PMS.dbg("rz_keywordMenuBtn.getName: menuRoot=null, name="+name);
				nm=name;
			}
			else if(menuRoot.dt_sc_str==null) {
				//PMS.dbg("rz_keywordMenuBtn.getName: menuRoot.dt_sc_str=null, name="+name);
				nm=name;
			}
			else {
				nm=name+" ["+menuRoot.dt_sc_str+"]";
			}
		}
		else if(dplist_cur && menuRoot.getCurrentList()!=null) {
			nm=name + " ["+menuRoot.getCurrentList().getName0()+"/]";
		}
		else if(dplist_def && menuRoot.getDefaultList()!=null) {
			nm=name + " ["+menuRoot.getDefaultList().getName0()+"/]";
		}
		else {
			nm=super.getName();
		}
		return nm;
	}
	
	@Override
	public String getName0 () {  //return bare name without decolations
		return super.getName();
	}

	@Override
	public boolean isTranscodeFolderAvailable() {
		return false;
	}

}
