/*
 * unity-webapps-resource-cache.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-resource-db.h"
#include "unity-webapps-resource-cache.h"
#include "unity-webapps-resource-factory.h"

#include "../unity-webapps-debug.h"


gchar *
unity_webapps_resource_cache_checksum_for_uri (const gchar *resource_uri)
{
  gchar *checksum;
  
  checksum = g_compute_checksum_for_string (G_CHECKSUM_MD5, resource_uri, -1);
  
  return checksum;
}


gchar *
unity_webapps_resource_cache_lookup_uri (const gchar *resource_uri)
{
  gchar *checksum, *path;
  
  UNITY_WEBAPPS_NOTE (RESOURCE, "Looking up URI (%s) in resource cache", resource_uri);
  
  if (resource_uri == NULL)
    {
      return NULL;
    }
  
  if (g_str_has_prefix (resource_uri, "icon://"))
    {
      UNITY_WEBAPPS_NOTE (RESOURCE, "Resource (%s) is a themed resource, skipping the cache", resource_uri);
      path = unity_webapps_resource_factory_resource_path_for_uri (resource_uri, TRUE);
      
      return path;
    }
  
  checksum = unity_webapps_resource_cache_checksum_for_uri (resource_uri);
  
  path = unity_webapps_resource_db_lookup_path (checksum);
  
  if (path == NULL)
    {
      UNITY_WEBAPPS_NOTE (RESOURCE, "Cache miss, creating new resource");

      path = unity_webapps_resource_factory_resource_path_for_uri (resource_uri, TRUE);
      
      if (path == NULL)
	{
	  UNITY_WEBAPPS_NOTE (RESOURCE, "Resource Cache failed to get resource path for URI: %s", resource_uri);
	  goto out;
	}
      
      UNITY_WEBAPPS_NOTE (RESOURCE, "Obtained resource file, storing entry in database for URI: %s", resource_uri);
      unity_webapps_resource_db_store_entry (checksum, path);
    }
#ifdef UNITY_WEBAPPS_ENABLE_DEBUG
  else
    {
      UNITY_WEBAPPS_NOTE (RESOURCE, "Cache hit for %s: %s", resource_uri, path);
    }
#endif

 out:
  g_free (checksum);
  
  return path;
}
