'use strict';

var $ = require('jquery');
var bootbox = require('bootbox');
var Raven = require('raven-js');
var ko = require('knockout');
var $osf = require('js/osfHelpers');
var oop = require('js/oop');
var ChangeMessageMixin = require('js/changeMessage');
var language = require('js/osfLanguage').projectSettings;

var ProjectSettings = oop.extend(
    ChangeMessageMixin,
    {
        constructor: function(params) {
            this.super.constructor.call(this);
            var self = this;

            self.title = ko.observable(params.currentTitle).extend({
                required: {
                    params: true,
                    message: 'Title cannot be blank.'
                }});
            self.description = ko.observable(params.currentDescription);
            self.titlePlaceholder = params.currentTitle;
            self.descriptionPlaceholder = params.currentDescription;

            self.disabled = params.disabled || false;

            if (!params.updateUrl) {
                throw new Error(language.instantiationErrorMessage);
            }

            self.categoryOptions = params.categoryOptions;
            self.categoryPlaceholder = params.category;
            self.selectedCategory = ko.observable(params.category);

            self.updateUrl = params.updateUrl;
            self.node_id = params.node_id;
        },
        /*error handler*/
        updateError: function(xhr, status, error) {
            var self = this;
            self.changeMessage(language.updateErrorMessage, 'text-danger');
            Raven.captureMessage(language.updateErrorMessage, {
                url: self.updateUrl,
                textStatus: status,
                err: error
            });
        },
        /*update handler*/
        updateAll: function() {
            var self = this;
            var requestPayload = self.serialize();
            var request = $osf.ajaxJSON('put', self.updateUrl, requestPayload);
            request.done(function(response) {
                self.selectedCategory(response.data.attributes.category);
                self.title(response.data.attributes.title);
                self.description(response.data.attributes.description);
                self.changeMessage(language.updateSuccessMessage, 'text-success')
            });
            request.fail(self.updateError.bind(self));
            return request;
        },
        /*cancel handler*/
        cancelAll: function() {
            var self = this;
            self.selectedCategory(self.categoryPlaceholder);
            self.title(self.titlePlaceholder);
            self.description(self.descriptionPlaceholder);
            self.resetMessage();
        },
        serialize: function() {
            var self = this;
            return {
                data: {
                    data: {
                        type: 'nodes',
                        id:   self.node_id,
                        attributes: {
                            title: self.title(),
                            category: self.selectedCategory(),
                            description: self.description(),
                        }
                    }
                },
                isCors: true
            }
        }
    });

// TODO: Pass this in as an argument rather than relying on global contextVars
var nodeApiUrl = window.contextVars.node.urls.api;

// Request the first 5 contributors, for display in the deletion modal
var contribs = [];
var moreContribs = 0;

var contribURL = nodeApiUrl + 'get_contributors/?limit=5';
var request = $.ajax({
    url: contribURL,
    type: 'get',
    dataType: 'json'
});
request.done(function(response) {
    // TODO: Remove reliance on contextVars
    var currentUserName = window.contextVars.currentUser.fullname;
    contribs = response.contributors.filter(function(contrib) {
        return contrib.shortname !== currentUserName;
    });
    moreContribs = response.more;
});
request.fail(function(xhr, textStatus, err) {
    Raven.captureMessage('Error requesting contributors', {
        url: contribURL,
        textStatus: textStatus,
        err: err,
    });
});


// function serialize() {
//     var self = this;
//     return {
//         data: {
//             data: {
//                 type: 'nodes',
//                 id:   'id',
//                 attributes: {
//                     title: self.title(),
//                     category: self.selectedCategory(),
//                     description: self.description(),
//                 }
//             }
//         },
//         isCors: true
//     }
// };

/**
 * Pulls a random name from the scientist list to use as confirmation string
 *  Ignores case and whitespace
 */
var getConfirmationCode = function(nodeType) {

    // It's possible that the XHR request for contributors has not finished before getting to this
    // point; only construct the HTML for the list of contributors if the contribs list is populated
    var message = '<p>It will no longer be available to other contributors on the project.';

    $osf.confirmDangerousAction({
        title: 'Are you sure you want to delete this ' + nodeType + '?',
        message: message,
        callback: function () {
            var request = $.ajax({
                type: 'DELETE',
                dataType: 'json',
                url: nodeApiUrl
            });
            request.done(function(response) {
                // Redirect to either the parent project or the dashboard
                window.location.href = response.url;
            });
            request.fail($osf.handleJSONError);
        },
        buttons: {
            success: {
                label: 'Delete'
            }
        }
    });
};

module.exports = {
    ProjectSettings: ProjectSettings,
    getConfirmationCode: getConfirmationCode
};

@@ -1922,39 +1922,111 @@
 ut',
- self.updateUrl, requestPayload
+%0A                self.updateUrl,%0A                %7B data: requestPayload,%0A                isCors: true %7D
 );%0A 
@@ -2091,33 +2091,38 @@
    self.
-selectedCategory(
+categoryPlaceholder = 
 response
@@ -2146,17 +2146,16 @@
 category
-)
 ;%0A      
@@ -2174,17 +2174,30 @@
 lf.title
-(
+Placeholder = 
 response
@@ -2218,17 +2218,16 @@
 es.title
-)
 ;%0A      
@@ -2248,25 +2248,38 @@
 .description
-(
+Placeholder = 
 response.dat
@@ -2294,32 +2294,210 @@
 utes.description
+;%0A                self.selectedCategory(self.categoryPlaceholder);%0A                self.title(self.titlePlaceholder);%0A                self.description(self.descriptionPlaceholder
 );%0A             
@@ -3084,40 +3084,8 @@
 : %7B%0A
-                    data: %7B%0A    
     
@@ -3115,20 +3115,16 @@
 nodes',%0A
-    
         
@@ -3167,36 +3167,32 @@
                 
-    
 attributes: %7B%0A  
@@ -3205,36 +3205,32 @@
                 
- 
-   
 title: self.titl
@@ -3230,28 +3230,24 @@
 lf.title(),%0A
-    
             
@@ -3309,36 +3309,32 @@
                 
-    
 description: sel
@@ -3354,34 +3354,8 @@
 (),%0A
-                        %7D%0A
     
@@ -3393,38 +3393,8 @@
    %7D
-,%0A                isCors: true
 %0A   
@@ -4319,465 +4319,8 @@
 );%0A%0A
-%0A// function serialize() %7B%0A//     var self = this;%0A//     return %7B%0A//         data: %7B%0A//             data: %7B%0A//                 type: 'nodes',%0A//                 id:   'id',%0A//                 attributes: %7B%0A//                     title: self.title(),%0A//                     category: self.selectedCategory(),%0A//                     description: self.description(),%0A//                 %7D%0A//             %7D%0A//         %7D,%0A//         isCors: true%0A//     %7D%0A// %7D;%0A%0A
 /**%0A

refactor serialize function and ajaxJSON request