/*
 * 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.
 */
//-----------------------------------------------------------------------------
// FolderType Buttons
// for the renderers that don't work well with FileType Buttons
//-----------------------------------------------------------------------------
package net.pms.dlna;

import net.pms.PMS;
import net.pms.dlna.rz_VirtualFolderButton;
import net.pms.dlna.RootFolder;

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

//public class rz_ClearFolderCache extends rz_VirtualFolderButton {
public class rz_ClearFolderCache extends rz_VirtualVideoActionF {
	private static final Logger logger = LoggerFactory.getLogger(rz_ClearFolderCache.class);
	private int mode;
	public DLNAResource targetDLNA=null;
	
	public rz_ClearFolderCache(String name, int mode) {
		//super(name);
		super(name,false,0,0);
		this.mode=mode;
	}

	@Override
	public int activate(int type) {
		if(PMS.rz_debug>1) PMS.dbg("rz_ClearFolderCache.activate: called, type="+type);
		if(type!=1 || targetDLNA==null) {
			return -1;
		}
		if(mode==1) {
			//clear MediaCache for only files direct under the folder
			RootFolder.ClearFolderChache(targetDLNA,mode);
		}
		else if(mode==2) {
			//clear MediaCache for all files & subfolders recursively
			RootFolder.ClearFolderChache(targetDLNA,mode);
		}
		else if(mode==3) {  // test for eazy way
			if(targetDLNA.getFolderCachePath()==null) {
				return -1;
			}
			if(!PMS.getConfiguration().getUseCache()) {
				return -1;
			}
			DLNAMediaDatabase db = PMS.get().getDatabase();
			if(db != null) {
				return -1;
			}
			//delete all childlen include subfolders
			String path=targetDLNA.getFolderCachePath();
			//SQL special char is generally, "'" ,"\", but may be more according to the DB software!!
			//Let's escape SQL's LIKE phrase special char(_,%), see DLNAMediaDatabase.delData()
			//in DLNAMediaDatabase.delData(), "<" used as escape char.
			path=path.replace("%", "<%").replace("_", "<_").replace("'", "<'"); 
			path=path+"%";
			if(PMS.rz_debug>1) PMS.dbg("rz_ClearFolderCache.activate: database.delData path="+path);
			db.delData(path,2); // 2: use wildcard
			targetDLNA.setDelayedClear(true);  //indicate clear the folder later
		}
		return 0;
	}
}

