/**
 * This offers the locally stored recordings (files) to the network
 */
package org.bucksch.zeipis.store;
import org.bucksch.httpserver.*;
import org.bucksch.zeipis.all.*;
import org.bucksch.zeipis.core.CoreServer;
import java.io.*;
import java.sql.*;
import java.util.Locale;

public class RecordingsManagementProvider implements HTTPHandler
{
  public RecordingsManagementProvider()
  {
    CoreServer.me.dispatchingServer().registerHandler(this, "recorded/management/delete/");
    CoreServer.me.dispatchingServer().registerHandler(this, "recorded/management/mark/");
  }
  public void handle(HTTPRequest request)
    throws HTTPException, IOException
  {
    int recordingid;    
    try {
      String recordingIDStr = request.getURLRest();
      recordingid = Integer.parseInt(recordingIDStr);
    } catch (Exception e) { throw new HTTPException(400, "Malformed URL value", e); }
    StoredRecording recording;
    try {
      recording = new StoredRecording(recordingid);
    } catch (Exception e) {  throw new HTTPException(400, "Cound not get recording with ID " + recordingid, e);  }

    if (request.getURLPrefix().equals("recorded/management/delete/"))
      delete(recording, request);
    else if  (request.getURLPrefix().equals("recorded/management/mark/"))
      mark(recording, request);
    else throw new HTTPException(500, "Unexpected URL");
  }

  protected void delete(StoredRecording recording, HTTPRequest request)
    throws HTTPException, IOException
  {
    if ( ! recording.store().isLocal())
      throw new HTTPException(500, "Deleting from remote stores not yet implemented"); // TODO

    File file = new File(recording.absFilename());
    boolean success = file.delete(); // actual delete
    if ( ! success)
      throw new HTTPException(500, "Could not delete file " + file.getAbsolutePath() + " on disk");

    // Mark as deleted in DB
    try {
      PreparedStatement deleteRecording = DB.me.database().prepareStatement("UPDATE recording SET deleted = TRUE WHERE recordid = ?");
      deleteRecording.clearParameters();
      deleteRecording.setInt(1, recording.id());
      deleteRecording.executeUpdate();
    } catch (SQLException e) { throw new HTTPException(500, "Could not update database, to mark recording as deleted", e); }

    done(request);
  }

  protected void mark(StoredRecording recording, HTTPRequest request)
    throws HTTPException, IOException
  {
    SimpleRFCParams params = new SimpleRFCParams().parseFromURL(request.getURL());
    markBoolean(recording.id(), "seen", params.param("seen"));
    markBoolean(recording.id(), "keep", params.param("keep"));

    if (params.param("broken") != null && params.param("broken").toLowerCase(Locale.ENGLISH).equals("true"))
    {
      markBoolean(recording.id(), "rerecord", "true");
      markBoolean(recording.id(), "done", "false");
      // schedule for re-recording
      try {
        PreparedStatement rerecord = DB.me.database().prepareStatement("INSERT INTO recording_plan (searchtype, recordid, priority) VALUES (2, ?, ?)");
        rerecord.clearParameters();
        rerecord.setInt(1, recording.id());
        rerecord.setInt(2, 0); // TODO priority (need to store in table recording)
        rerecord.executeUpdate();
        // TODO run scheduler
      } catch (SQLException e) { throw new HTTPException(500, "Could not update database to re-record the broken recording", e); }
    }
    done(request);
  }
  protected void markBoolean(int recordingid, String fieldname, String value)
    throws HTTPException
  {
    if (value == null)
      return;
    if ( ! (value.toLowerCase(Locale.ENGLISH).equals("true") || value.toLowerCase(Locale.ENGLISH).equals("false")))
      throw new HTTPException(400, "Malformed parameter for " + fieldname + ". true or false expected.");
    try {
      DB.me.database().createStatement().executeUpdate("UPDATE recording SET "
              + fieldname + " = " + value + " WHERE recordid = " + recordingid);
    } catch (SQLException e) { throw new HTTPException(500, "Cound not update database, to mark recording as " + fieldname, e); }
  }
  
  protected void done(HTTPRequest request)
    throws HTTPException, IOException
  {
    request.sendResponseHeaders(200, false);
    request.getResponseBody().close();
  }
}
