package com.ytdl.conversion;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.UUID;

import com.ytdl.YtdlConstants;
import com.ytdl.api.SessionHandler;

public class VideoDownloader {
	private static boolean debug = true;

	/**
	 * 
	 * @param url YT video url
	 * @param id id of session
	 * @param i element of session
	 * @return
	 */
	public static boolean download(String url, UUID id, int i) {
		boolean downloadSuccess = false;
		InputStream stdout = null;
		InputStream stderr = null;
		InputStreamReader isr = null;
		InputStreamReader isrE = null;
		BufferedReader br = null;
		BufferedReader brE = null;
		try {

			// TODO: try doing this with the -o command....
			ProcessBuilder pb = new ProcessBuilder("youtube-dl", url, "-x", "--audio-format=mp3", "--no-playlist", "-o",
					YtdlConstants.content_directory + "%(title)s-%(id)s.%(ext)s");

			Process proc = pb.start();

			stdout = proc.getInputStream();
			stderr = proc.getInputStream();
			isr = new InputStreamReader(stdout);
			isrE = new InputStreamReader(stderr);
			br = new BufferedReader(isr);
			brE = new BufferedReader(isrE);
			String outLine = null;
			String errLine = null;
			while ((outLine = br.readLine()) != null || (errLine = brE.readLine()) != null) {
				if (outLine.startsWith("[ffm")) {
					SessionHandler.updateRequest(id, i, SessionHandler.STATUS_CONVERTING);
					// break;
				} else if (outLine.startsWith("Deleting")) {
					downloadSuccess = true;
					// break;
				}
				if (debug) {
					if (outLine != null)
						System.out.println("[Debug] " + outLine);
					if (errLine != null)
						System.err.println("<Error>" + errLine + "<Error>");
				}
			}

		} catch (Throwable t) {
			t.printStackTrace();
		} finally {
			try {
				stdout.close();
				stderr.close();
				isr.close();
				isrE.close();
				br.close();
				brE.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return downloadSuccess;
	}

	private VideoDownloader() {
	}
}

@@ -330,16 +330,31 @@
 aram url
+%0A%09 *           
  YT vide
@@ -372,16 +372,31 @@
 param id
+%0A%09 *           
  id of s
@@ -414,16 +414,31 @@
 @param i
+%0A%09 *           
  element
@@ -751,17 +751,45 @@
 %09%09try %7B%0A
+%09%09%09ProcessBuilder pb = null;
 %0A
-
 %09%09%09// TO
@@ -830,39 +830,262 @@
 mand....%0A%09%09%09
-ProcessBuilder 
+if (System.getProperty(%22os.name%22).equals(%22Linux%22)) %7B%0A%09%09%09%09pb = new ProcessBuilder(%22./youtube-dl%22, url, %22-x%22, %22--audio-format=mp3%22, %22--no-playlist%22, %22-o%22,%0A%09%09%09%09%09%09YtdlConstants.content_directory + %22%25(title)s-%25(id)s.%25(ext)s%22);%0A%09%09%09%7D else %7B%0A%09%09%09%09
 pb = new Pro
@@ -1167,24 +1167,25 @@
  %22-o%22,%0A%09%09%09%09%09
+%09
 YtdlConstant
@@ -1234,16 +1234,21 @@
 ext)s%22);
+%0A%09%09%09%7D
 %0A%0A%09%09%09Pro

Add support for youtube-dl execution on Linux ./