###

Functions to manage our Assets on the site with Rackspaces Cloud Files
or any other we latter decide for.

###
uuid = require 'node-uuid'
path = require 'path'
http = require 'http'
url = require 'url'
cloudfiles = require 'cloudfiles'

# Object to return
asset_manager = Object();

###
Get the Authenticated Client for the service.
###
asset_manager.get_client = (username, key, host, cdn_url, container_name, fn) ->

	###
	Create our Clients Files Client
	###
	client = cloudfiles.createClient {
			auth: {
				username: username,
				apiKey: key,
				host: host
			}
		}

	# Set Params for use later
	client.cdn_url = cdn_url
	client.container = container_name

	###
	Authenticate with our Properties
	###
	client.setAuth (err) ->
		fn err, client

###
Check for the location of the file and returns a full url to the file in our CDN.

If no file was found we return the fallback url
###
asset_manager.get = (client, filename, fallback, fn) ->

	if filename

		if filename.indexOf('http') != -1 or filename.indexOf('https') != -1
			fn filename # We don't check remote files!
		else
			asset_manager.exist filename, (result) ->

				# If their fallback is a function we just return a false. Else we return the file.

				if typeof fallback == 'function' && !fn

					if result
						fn filename
					else
						fn false

				else

					# If their fallback was string. This method is used to generated display images.

					if result
						fn client.cdn_url + "/" + filename
					else
						fn fallback

	else
		fn fallback

###
Forwards a Boolean whether the file was found on our cdn or not.
###
asset_manager.exist = (client, filename, fn) ->
	options = url.parse(client.cdn_url + "/" + filename)
	options.method = 'HEAD'

	req = http.request options, (res) ->
		fn res.statusCode == 200

	req.end()

###
Deletes the File with thtat name.
###
asset_manager.remove = (client, filename, fn) ->
	client.getContainer client.container_name, (err, container_obj) ->
		if err
			fn false
		else
			container_obj.removeFile client.filename, (err) ->
				fn true

###
Uploads the File to the CDN. This would normally be called by the server handling the file 
upload to add the file to the CDN after it's been received. The server would then delete the 
File from it's local system. 

At the moment we use Rackspace CloudFiles.

This allows us to:
1 -> Use a CDN for faster performance.
2 -> Keep the entire movable to any number of configuration without worrying about the files. 
3 -> Let another provider povide us with backups. Don't like them and have never been good at them :P
###
asset_manager.put = (client, filename, file_path, fn) ->
	remote_filename = uuid.v4() + path.extname filename

	fs.exists file_path, (exists) ->
		if exists

			client.addFile container_name, { remote: remote_filename, local: file_path }, (err, uploaded) ->
				fn null, remote_filename

		else
			fn 'No Such File', null

# Assign our Object
module.exports = exports =  asset_manager
	