/*
 * 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 java.net.MalformedURLException;
import java.net.URL;

import net.pms.network.HTTPResourceAuthenticator;
import net.pms.PMS;	//regzamod
import net.pms.formats.Format;
import net.pms.util.StringUtil;

/**
 * TODO: Change all instance variables to private. For backwards compatibility
 * with external plugin code the variables have all been marked as deprecated
 * instead of changed to private, but this will surely change in the future.
 * When everything has been changed to private, the deprecated note can be
 * removed.
 */
public class WebStream extends DLNAResource {
	public String[] param_cache;
	public long param_cache_date;
	//private boolean under_web_folder;
	
	@Override
	protected void checktype() {
		//origin: will fail judge, if url's tail has valid mime_type suffix (ex: .mp4, .asf etc)
		/*
		if (getExt() == null) {
			setExt(PMS.get().getAssociatedExtension(getSystemName()));
		}
		if (getExt() != null) {
			if (getExt().isUnknown()) {
				getExt().setType(getSpecificType());
			}
		}
		*/
		if(getExt()==null) { 
			setExt(PMS.get().getAssociatedExtension("http://dummy"));  //force web sream
		}
		if(getExt() != null) {
			if (getExt().isUnknown()) {
				getExt().setType(getSpecificType());
			}
		}
	}

	@Override
	public boolean isValid() {
		checktype(); 
		return getExt() != null;
	}

	/**
	 * @deprecated Use standard getter and setter to access this variable.
	 */
	@Deprecated
	protected String url;

	/**
	 * @deprecated Use standard getter and setter to access this variable.
	 */
	@Deprecated
	protected String fluxName;

	/**
	 * @deprecated Use standard getter and setter to access this variable.
	 */
	@Deprecated
	protected String thumbURL;

	//---- regzamod start
	protected String[] url_params;	
	
	public void setUrlParamsString(String s) {
		if(s==null) return;
		String s1="dummy_name,dummy_url,dummy_thumb,"+s;
		url_params=s1.split(",");
		
		if(getParent()!=null) {
			setAudioTagsFromUrlParams(getParent().getUrlParams());
		}
		setAudioTagsFromUrlParams(url_params);
	}
	public void setUrlParams(String[] up, String cs) {
		//PMS.dbg("WebStream: setUrlParams p="+p+ ", length="+(p==null?0:p.length));
		
		if(PMS.rz_debug>1) {
			PMS.dbg("==== WebStream.setUrlParams: setUrlParams up="+up+", cs="+cs);
			if(up!=null && up.length>3) {
				for(int i=3;i<up.length;i++) {
					PMS.dbg("WebStream: param up("+i+") ="+up[i]);
				}
			}
			PMS.dbg("WebStream: param cs="+cs);
		}
		
		// make StringArray for cs
		String[] cp=null;
		if(cs!=null) {
			cp=cs.split(",");
		}
		
		//concat p,cp
		//up:valid from [3] for opts, i.e. [0]:name, [1]:url, [2]:thumb, [3]:opts,...
		url_params=StringUtil.StrArrayConcat(cp,up,0,3);
		
		if(PMS.rz_debug>1) {
			if(url_params!=null && url_params.length>0) {
				for(int i=0;i<url_params.length;i++) {
					PMS.dbg("WebStream.setUrlParams: param("+i+") ="+url_params[i]);
				}
			}
		}
		
		//set 
		if(getParent()!=null) {
			setAudioTagsFromUrlParams(getParent().getUrlParams());
		}
		setAudioTagsFromUrlParams(url_params);
	}
	
	/* moved to StringUtil.java
	private String [] StrArrayConcat(String[] ps1,String[] ps2) {
		if(ps1!=null) {
			if(ps2!=null) {
				String[] ps3 = new String[ps1.length + ps2.length];
				System.arraycopy(ps1,0,ps3,0,ps1.length); 
				System.arraycopy(ps2,0,ps3,ps1.length,ps2.length); 
				return ps3;
			}
			else {
				return ps1;
			}
		}
		else {
			return ps2;
		}
	}
	*/
	
	private void setAudioTagsFromUrlParams(String[] url_params) {
		if(url_params==null) return;
		if(getSpecificType()== Format.AUDIO) {
			DLNAMediaAudio audio=getMediaAudio(); //get only primary audio
			for(int i=0;i<url_params.length;i++) {
				if(url_params[i].equals("--genre") && i<url_params.length-1) {
					audio.setGenre(url_params[i+1].trim());
				};
			}
		}
	}
	
	@Override
	public String[] getUrlParams() {
		if(getParent()!=null) {
			return StringUtil.StrArrayConcat(getParent().getUrlParams(),url_params,0,0);
		}
		return url_params;
	}
	
	@Override
	public String getUrlParamsString() {
		if(url_params==null) return null;
		String s="";
		for(int i=0;i<url_params.length;i++) {
			s+=","+url_params[i];
		}
		if(s.length()>0) {
			s=s.substring(1,s.length());
		}
		else {
			s=null;
		}
		return s;
	}
	
	public boolean needReCreate() {
		if(PMS.rz_debug>1) PMS.dbg("rz_WebStream.needReCreate: Start");
		if(rz_Metafile!=null) {
			boolean b=(getLastmodified() < rz_Metafile.lastModified());
			if(PMS.rz_debug>1) PMS.dbg("rz_WebStream.needReCreate: End-1, rc="+b);
			return (b);
		}
		else {
			if(PMS.rz_debug>1) PMS.dbg("rz_WebStream.needReCreate: End-2, rc=false");
			return false;
		}
	}
	//---- regzamod end

	public WebStream(String fluxName, String url, String thumbURL, int type) {
		super(type);
		if(PMS.rz_debug>1) PMS.dbg("WebStream: fluxName="+fluxName+", url="+url+", thumbURL="+thumbURL);

		try {
			URL tmpUrl = new URL(url);
			tmpUrl = HTTPResourceAuthenticator.concatenateUserInfo(tmpUrl);
			setUrl(tmpUrl.toString());
		} catch (MalformedURLException e) {
			setUrl(url);
		}
		
		if(getMedia()==null) {
			setMedia(new DLNAMediaInfo());
		}

		if(thumbURL!=null) {
			//PMS.dbg("WebStream: thumbURL!=null, url="+url);
			String turl=thumbURL.trim();
			if(turl.length()>0) {
				try {
					URL tmpUrl = new URL(turl);
					tmpUrl = HTTPResourceAuthenticator.concatenateUserInfo(tmpUrl);
					setThumbURL(tmpUrl.toString());
				} catch (MalformedURLException e) {
					setThumbURL(turl);
				}
			}
			//PMS.dbg("WebStream: thumbURL="+thumbURL+", converted="+this.thumbURL);
		}
		setFluxName(fluxName);
	}

	@Override
	public InputStream getThumbnailInputStream() throws IOException {
		
		DLNAMediaInfo med=getMedia();
		//PMS.dbg("WebStream.getThumbnailInputStream: called");
		
		if (getThumbURL() != null) {
			if(PMS.rz_debug>1) PMS.dbg("WebStream.getThumbnailInputStream: name="+getName()+", getThumbURL() != null --> return downloadAndSend(getThumbURL())");
			return downloadAndSend(getThumbURL(), true);
		} 
		else if(med!=null && med.getThumb()!=null) {
			if(PMS.rz_debug>1) PMS.dbg("WebStream.getThumbnailInputStream: name="+getName()+", getThumb()!=null --> return this.getThumbnailInputStream()");
			return med.getThumbnailInputStream();
		}
		else {
			if(PMS.rz_debug>1) PMS.dbg("WebStream.getThumbnailInputStream: name="+getName()+", getThumb()==null --> return super.getThumbnailInputStream()");
			return super.getThumbnailInputStream();
		}
	}

	public InputStream getInputStream() {
		return null;
	}

	public long length() {
		return DLNAMediaInfo.TRANS_SIZE;
	}

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

	public boolean isFolder() {
		return false;
	}

	public long lastModified() {
		return 0;
	}

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

	@Override
	public String getSrcPath() {	//regzamod, add
		return url;
	}
	
	
	/*
	public String getResumePath_old() {	//regzamod, add
		if(resume_path!=null) return resume_path;

		String path=null;
		DLNAResource pa=getParent();
		while (pa!=null) {
			if((pa.mflags & DLNAResource.MF_WEB_RESUME_FOLDER)!=0) {
				under_web_folder=true;
				path=pa.getResumePath();
				break;
			}
			pa=pa.getParent();
		}
		if(path!=null) {  //under WebFolder
			path=path+"/dummy";		//per individual webfolder
		}
		else if(pa!=null) {  //under realFolder
			path=pa.getSrcPath()+"/dummy";
		}
		else {
			path=url;
		}
		resume_path=path;
		if(PMS.rz_debug>1) PMS.dbg("WebStream: getResumePath="+path);
		return path;
	}
	*/

	/**
	 * @return the url
	 * @since 1.50
	 */
	protected String getUrl() {
		return url;
	}

	/**
	 * @param url the url to set
	 * @since 1.50
	 */
	protected void setUrl(String url) {
		this.url = url;
	}

	/**
	 * @return the fluxName
	 * @since 1.50
	 */
	protected String getFluxName() {
		return fluxName;
	}

	/**
	 * @param fluxName the fluxName to set
	 * @since 1.50
	 */
	protected void setFluxName(String fluxName) {
		this.fluxName = fluxName;
	}

	/**
	 * @return the thumbURL
	 * @since 1.50
	 */
	protected String getThumbURL() {
		return thumbURL;
	}

	/**
	 * @param thumbURL the thumbURL to set
	 * @since 1.50
	 */
	protected void setThumbURL(String thumbURL) {
		this.thumbURL = thumbURL;
	}
}
