'use strict';

var module = angular.module('csbooks.services', ['csbooks.models']);

module.factory('Books', ['$resource', 'Book', function($resource, Book) {
    var Books = $resource('http://localhost:3000/api/books/:id', { id:'@id'}, {
        update: {
            method: 'PUT'
        }
    });

    return {
        findAll: function(callback) {
            var result = [];
            var books = Books.query(function() {
                for(var i=0; i<books.length; i++) {
                    result.push(new Book(books[i]));
                }
                callback(result);
            });
        },
        findById: function(id, callback) {
            Books.get({id: id}, function(data) {
                callback(new Book(data))
            });
        },
        update: function(obj, callback) {
            Books.update(_toModel(obj), callback);
        },
        delete: function(id, callback) {
            Books.delete({id: id}, callback);
        },
        create: function(obj, callback) {
            Books.save(_toModel(obj), function(data, responseHeaders) {
                callback(responseHeaders('Location').split('/').pop());
            });
        },
        newInstance: function() {
            return new Book({});
        },
        export: function(books) {
            var result = [];
            angular.forEach(books, function(book) {
                result.push(_toCsvModel(book));
            }, result);
            return result;
        }
    }

    function _toModel(book) {
        return {
            id: book.id,
            title: book.title,
            authors: book.authors.split(', '),
            orderedFor: book.orderedFor,
            orderDate: _toDate(book.orderDate),
            isbn10: book.isbn._10.value,
            isbn13: book.isbn._13.value
        }
    }

    function _toCsvModel(book) {
        return {
            title: book.title,
            authors: book.authors,
            orderedFor: book.orderedFor,
            orderDate: book.orderDate,
            isbn10: book.isbn._10.value,
            isbn13: book.isbn._13.value
        }
    }

    function _toDate(value) {
        console.log(value);
        if(value && value.length > 0) {
            var parts = value.split('.');
            console.log(parts);
            return new Date(parts[2], parts[1]-1, parts[0], 14, 0, 0, 0);
        }
        return "";
    }
}]);