package com.upc.pbe.upcnews;

import java.io.File;
import java.util.ArrayList;

import android.util.Log;

//Gestor del protocol HTTP Live Streaming
public class HLS
{

	private static final String TAG = "HLS";
	private ArrayList<ParentList> videos;
	private ArrayList<Segment> segments;
	private ArrayList<Video> qualities;
	private int currentVideo;
	private int currentQuality; // 0 es la mas alta
	private int currentSegment;
	private boolean endReached;
	private int defaultQuality;
	private boolean setDefault;

	public HLS(ArrayList<ParentList> parsed, String localFolder)
	{
		// Neteja el directori i inicialitza les variables
		File dir = new File(localFolder);
		String[] files = dir.list();
		for (int i = 0; i < files.length; i++)
		{
			File deleteme = new File(dir, files[i]);
			Log.d(TAG, "Esborrat " + files[i].toString());
			deleteme.delete();
		}

		currentVideo = currentSegment = 0;
		this.videos = parsed;
		endReached = false;
		setDefault = true;
	}

	public void setQuality(int qual)
	{
		defaultQuality = qual;
	}

	public void loadVideo()
	{
		// Carrega la qualitat i, a partir d'aixo, el seguent segment
		qualities = videos.get(currentVideo++).getLists();
		if(setDefault)
		{
			switch (defaultQuality)
			{
			case 0:
				currentQuality = 0;
				break;
			case 1:
				currentQuality = (qualities.size())/2;
				break;
			case 2:
				currentQuality = qualities.size()-1;
				break;
			}
		}
		setDefault = true;
		segments = qualities.get(currentQuality).getSegments();
		if (currentVideo == videos.size())
		{
			endReached = true;
		}
	}

	public String next()
	{
		// Determina la seguent qualitat a partir de la velocitat
		if (currentSegment == segments.size())
		{
			if (endReached)
			{
				return null;
			};
			currentSegment = 0;
			loadVideo();
		}
		Segment seg = segments.get(currentSegment++);
		Log.d(TAG, seg.getName() + " " + seg.getURL());
		return seg.getURL();
	}

	public void updateQuality(long bps)
	{
		if ((bps <= qualities.get(currentQuality).getQuality()) && (bps != -1))
		{
			int newQuality;
			for (newQuality = 0; newQuality < qualities.size(); newQuality++)
			{
				if (bps >= qualities.get(newQuality).getQuality())
				{
					break;
				}
			}
			if (currentQuality != newQuality)
			{
				setDefault = false; //Override
				currentQuality = newQuality;
				currentVideo--; // Corregimos el del loadVideo()
				loadVideo(); // Cargamos la nueva calidad
			}
		}
		else if ((bps > qualities.get(currentQuality).getQuality())
				&& (bps != -1))
		{
			int newQuality;
			for (newQuality = qualities.size() - 1; newQuality > 0; newQuality--)
			{
				if (bps <= qualities.get(newQuality).getQuality())
				{
					newQuality--;
					break;
				}
			}
			if (currentQuality != newQuality)
			{
				setDefault = false;
				currentQuality = newQuality;
				currentVideo--; // Corregimos el del loadVideo()
				loadVideo(); // Cargamos la nueva calidad
			}
		}
	}

}
