var ViewModel = function () {
    var self = this;
    self.books = ko.observableArray();
    self.error = ko.observable();
    self.book = ko.observable();
    self.newBook = {
        Author: ko.observable(),
        Genre: ko.observable(),
        Price: ko.observable(),
        Title: ko.observable(),
        Year: ko.observable()
    }
    self.authors = ko.observableArray();

    var authorsUri = '/api/authors/';
    var booksUri = '/api/books';

    function ajaxRequestHelper(uri, method, data) {
        self.error('');

        return $.ajax({
            type: method,
            url: uri,
            dataType: 'json',
            contentType: 'application/json',
            data: data ? JSON.stringify(data) : null
        }).fail(function (jqXHR, textStatus, errorThrown) {
            self.error(errorThrown);
        });
    }

    function getAllBooks() {
        ajaxRequestHelper(booksUri, 'GET').done(function (data) {
            self.books(data);
        });
    }

    self.getBookDetail = function (item) {
        ajaxRequestHelper(booksUri + '/' + item.Id, 'GET').done(function (data) {
            self.book(data);
            console.log(data);
        });
    }

    function getAuthors() {
        ajaxRequestHelper(authorsUri, 'GET').done(function (data) {
            self.authors(data);
        });
    }

    self.addBook = function (formElement) {
        var book = {
            AuthorId: self.newBook.Author().Id,
            Genre: self.newBook.Genre(),
            Price: self.newBook.Price(),
            Title: self.newBook.Title(),
            Year: self.newBook.Year()
        };

        ajaxRequestHelper(booksUri, 'POST', book).done(function (item) {
            self.books.push(item);
        });
    }

    getAuthors();
    getAllBooks();

};
ko.applyBindings(new ViewModel());