 Errors = require("./Errors")
 _ = require("underscore")
 awsS3 = require "aws-sdk/clients/s3"
+URL = require('url')
 
 thirtySeconds = 30 * 1000
 
 buildDefaultOptions = (bucketName, method, key)->
+	if settings.filestore.s3.endpoint
+		endpoint = "#{settings.filestore.s3.endpoint}/#{bucketName}"
+	else
+		endpoint = "https://#{bucketName}.s3.amazonaws.com"
 	return {
 			aws:
 				key: settings.filestore.s3.key

				bucket: bucketName
			method: method
			timeout: thirtySeconds
			uri:"https://#{bucketName}.s3.amazonaws.com/#{key}"
	}

defaultS3Client = new awsS3({
	credentials:
		accessKeyId: settings.filestore.s3.key,
		secretAccessKey: settings.filestore.s3.secret
})

getS3Client = (credentials) ->
	if credentials?
		return new awsS3({
			credentials:
				accessKeyId: credentials.auth_key
				secretAccessKey: credentials.auth_secret
		})
	else
		return defaultS3Client

module.exports =

	sendFile: (bucketName, key, fsPath, callback)->
		s3Client = knox.createClient
			key: settings.filestore.s3.key
			secret: settings.filestore.s3.secret
			bucket: bucketName
		putEventEmiter = s3Client.putFile fsPath, key, (err, res)->
			if err?
				logger.err err:err,  bucketName:bucketName, key:key, fsPath:fsPath,"something went wrong uploading file to s3"

			_callback = () ->

		logger.log key: key, bucketName: bucketName, "deleting directory"
		s3Client = getKnoxClient(bucketName)
		s3Client.list prefix:key, (err, data)->
			if err?
				logger.err err:err, bucketName:bucketName, key:key, "something went wrong listing prefix in aws"
