/*
 * unity-webapps-gio-utils.c
 * Copyright (C) Canonical LTD 2011
 *
 * Author: Robert Carr <racarr@canonical.com>
 * 
 unity-webapps is free software: you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published
 * by the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * unity-webapps 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 Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.";
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <glib/gstdio.h>
#include <gio/gio.h>

#include "unity-webapps-dirs.h"
#include "unity-webapps-gio-utils.h"
#include "../unity-webapps-debug.h"

gboolean
unity_webapps_gio_utils_splice_files (GFile *resource_file,
				      GFile *local_resource_file)
{
  GInputStream *input_stream;
  GOutputStream *output_stream;
  GError *error;
  gboolean ret;
  
  error = NULL;
  
  input_stream = G_INPUT_STREAM (g_file_read (resource_file, NULL /* Cancellable */, &error));
  
  if (error != NULL)
    {
      g_warning ("Error reading resource file to save: %s", error->message);
      g_error_free (error);
      
      return FALSE;
    }
  
  output_stream = G_OUTPUT_STREAM (g_file_replace (local_resource_file, NULL, FALSE, G_FILE_CREATE_REPLACE_DESTINATION, NULL /* Cancellable */, &error));
  
  if (error != NULL)
    {
      UNITY_WEBAPPS_NOTE (RESOURCE, "Error opening temporary file to save resource: %s", error->message);
      
      g_error_free (error);
      
      g_object_unref (G_OBJECT (input_stream));
      
      return FALSE;
    }

  g_output_stream_splice (output_stream, input_stream, G_OUTPUT_STREAM_SPLICE_CLOSE_SOURCE |
			  G_OUTPUT_STREAM_SPLICE_CLOSE_TARGET, NULL /* Cancellable */,
			  &error);
  
  ret = TRUE;
  
  if (error != NULL)
    {
      g_warning ("Error writing open resource file to saved file: %s", error->message);
      
      g_error_free (error);
      
      ret = FALSE;
    }
  
  g_object_unref (G_OBJECT (input_stream));
  g_object_unref (G_OBJECT (output_stream));
  
  return ret;
}
