package @APP_PACKAGE@.content;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.ParcelFileDescriptor;
import android.util.Log;
import android.util.TimingLogger;

import @APP_PACKAGE@.XBMCProperties;

public class XBMCYTDLContentProvider extends XBMCContentProvider
{
  private static String TAG = "@APP_NAME@_YTDL_Provider";

  public static String AUTHORITY = AUTHORITY_ROOT + ".ytdl";

  @Override
  public boolean onCreate()
  {
    return true;
  }

  public static Uri GetYTDLUri(String surl)
  {
    if (surl == null)
      return null;
    if (surl.isEmpty())
      return null;

    Uri.Builder builder = new Uri.Builder();
    builder.scheme("content")
            .authority(AUTHORITY)
            .fragment(surl);

    Uri out = builder.build();
    return out;
  }

  private static String getFinalURL(String url) throws IOException
  {
    TimingLogger timings = new TimingLogger(TAG, "XBMCYTDLContentProvider::getFinalURL");

    HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
    con.setInstanceFollowRedirects(false);
    con.connect();
    timings.addSplit("connect");

    con.getInputStream();
    timings.addSplit("response");

    if (con.getResponseCode() == HttpURLConnection.HTTP_MOVED_PERM || con.getResponseCode() == HttpURLConnection.HTTP_MOVED_TEMP)
    {
      String redirectUrl = con.getHeaderField("Location");
      return getFinalURL(redirectUrl);
    }

    timings.addSplit("done");
    timings.dumpToLog();

    return url;
  }

  @Override
  public ParcelFileDescriptor openFile(Uri uri, String mode)
          throws FileNotFoundException
  {
    ParcelFileDescriptor[] pipe = null;

    try
    {
      String decodedUrl = uri.getFragment();
      if (decodedUrl == null)
      {
        return null;
      }

      String finalURL = "";
      try
      {
        finalURL = getFinalURL(decodedUrl);
      }
      catch (Exception e)
      {
        e.printStackTrace();
        return null;
      }

      pipe = ParcelFileDescriptor.createPipe();

      URL url = new URL(finalURL);
      HttpURLConnection connection = (HttpURLConnection) url.openConnection();

      connection.setDoInput(true);
      connection.connect();

      new TransferThread(connection.getInputStream(),
              new ParcelFileDescriptor.AutoCloseOutputStream(pipe[1])).start();
    }
    catch (IOException e)
    {
      Log.e(getClass().getSimpleName(), "Exception opening pipe", e);
      throw new FileNotFoundException("Could not open pipe for: "
              + uri.toString());
    }

    return (pipe[0]);
  }

  @Override
  public Cursor query(Uri uri, String[] projection, String selection,
                      String[] selectionArgs, String sortOrder)
  {
    return null;
  }

  @Override
  public String getType(Uri uri)
  {
    return "video/*";
  }

  @Override
  public Uri insert(Uri uri, ContentValues values)
  {
    return null;
  }

  @Override
  public int delete(Uri uri, String selection, String[] selectionArgs)
  {
    return 0;
  }

  @Override
  public int update(Uri uri, ContentValues values, String selection,
                    String[] selectionArgs)
  {
    return 0;
  }

  static class TransferThread extends Thread
  {
    InputStream in;
    OutputStream out;

    TransferThread(InputStream in, OutputStream out)
    {
      this.in = in;
      this.out = out;
    }

    @Override
    public void run()
    {
      byte[] buf = new byte[8192];
      int len;

      try
      {
        while ((len = in.read(buf)) >= 0)
        {
          out.write(buf, 0, len);
        }

        out.flush();
      }
      catch (IOException e) {}
      finally
      {
        try
        {
          in.close();
          out.close();
        }
        catch (IOException e) {}
      }
    }
  }

}
