/*
 * 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.File;
import java.util.List;
import java.util.Date;

import net.pms.PMS;
import net.pms.dlna.virtual.VirtualFolder;
import net.pms.formats.Format;
import net.pms.io.OutputParams;
import net.pms.io.ProcessWrapperImpl;
import net.pms.util.ProcessUtil;

import org.slf4j.Logger;			//regzamod
import org.slf4j.LoggerFactory;		//regzamod

public class DVDISOFile extends VirtualFolder {
	public static final String PREFIX = "[DVD ISO] ";
	private static final Logger logger = LoggerFactory.getLogger(DVDISOFile.class);	//regzamod
	//private boolean resolved;
	private File f;
	private File cfs[];

	public DVDISOFile(File f) {
		super(PREFIX + (f.isFile() ? f.getName() : "VIDEO_TS"), null);
		this.f = f;
		setLastmodified(f.lastModified());
		if(PMS.rz_debug>1) PMS.dbg("DVDISOFile.constructor: file="+f);
	}
	
	/*
	@Override
	public boolean allowScan() {
		return true;
	}
	*/
	//called as a child of parent folder
	private boolean needRefresh() {	//add regzamod
		//PMS.dbg("DVDISOFile.needRefresh: called resolved="+resolved);
		if(!resolved) {
			//PMS.dbg("DVDISOFile.needRefresh: not resolved --> return true");
			return true;
		}
		File cfs_new[]=f.listFiles();
		
		if(cfs==null && cfs_new!=null) {
			cfs=cfs_new;
			return true;	// contents differ
		}
		if(cfs!=null && cfs_new==null) {
			cfs=cfs_new;
			return true;	// contents differ
		}
		if(!cfs.equals(cfs_new)) { // not same values
			cfs=cfs_new;
			return true;
		}
		return false;
		
	}
	
	//called as a folder, before opening the folder
	@Override
	public boolean isRefreshNeeded() {
		//PMS.dbg("DVDISOFile.isRefreshNeeded: called, resolved="+resolved);
		if(!resolved) return true;
		return false;
	}

	//called if isRefreshNeeded() returned true
	@Override
	public void refreshChildren() {
		//PMS.dbg("DVDISOFile.refreshChildren: called, resolved="+resolved);
		if(!resolved) resolve();
	}

	@Override
	public void resolve() {
		double titles[] = new double[100];
		
		//PMS.dbg("DVDISOFile.resolve: called, file="+f.getAbsolutePath());

		if(resolved && getLastmodified()==f.lastModified()) {
			//PMS.dbg("DVDISOFile.resolve: already resolved");
			return;
		}
		else {
			setLastmodified(f.lastModified());
			resolved=true;  //would be resolved
		}
		//PMS.dbg("DVDISOFile.resolve: exec resolve");
		
		//Once, delete all children, othewise old children remain !!		
		//all childlen will be re-created by following AddChild 
		this.getChildren().clear();	// regzamod
		deleteMenus();

		String cmd[] = new String[]{PMS.getConfiguration().getMplayerPath(), "-identify", "-endpos", "0", "-v", "-ao", "null", "-vc", "null", "-vo", "null", "-dvd-device", ProcessUtil.getShortFileNameIfWideChars(f.getAbsolutePath()), "dvd://1"};
		OutputParams params = new OutputParams(PMS.getConfiguration());
		params.maxBufferSize = 1;
		params.log = true;
		final ProcessWrapperImpl pw = new ProcessWrapperImpl(cmd, params, true, false);
		Runnable r = new Runnable() {
			public void run() {
				try {
					Thread.sleep(10000);
				} catch (InterruptedException e) {
				}
				pw.stopProcess();
			}
		};
		Thread failsafe = new Thread(r);
		failsafe.start();
		pw.run();
		List<String> lines = pw.getOtherResults();
		if (lines != null) {
			for (String line : lines) {
				if (line.startsWith("ID_DVD_TITLE_") && line.contains("_LENGTH")) {
					int rank = Integer.parseInt(line.substring(13, line.indexOf("_LENGT")));
					double duration = Double.parseDouble(line.substring(line.lastIndexOf("LENGTH=") + 7));
					titles[rank] = duration;
				}
			}
		}

		double oldduration = -1;

		for (int i = 1; i < 99; i++) {
			// don't take into account titles less than 10 seconds
			// also, workaround for the mplayer bug which reports several times an unique title with the same length
			// The "maybe wrong" title is taken into account only if his length is smaller than 1 hour.
			// Common sense is a single video track on a DVD is usually greater than 1h
			if (titles[i] > 10 && (titles[i] != oldduration || oldduration < 3600)) {
				DVDISOTitle dvd = new DVDISOTitle(f, i);
				logger.debug("DVDtitle i="+i+", f="+f.getName()+", dvdinfo="+dvd);	// regzamod
				addChild(dvd);
				oldduration = titles[i];
			}
		}

		/*
		if (childrenNumber() > 0) {
			PMS.get().storeFileInCache(f, Format.ISO);
		}
		*/
	}

	@Override
	public String getDisplayName() {
		String s = super.getDisplayName();
		if (f.getName().toUpperCase().equals("VIDEO_TS")) {
			s += " {" + f.getParentFile().getName() + "}";
		}
		return s;
	}
	
	@Override
	public String getSrcPath() {	//regzamod, add
		return f.getAbsolutePath();
	}

}

