var m = require('mithril');
var Raven = require('raven-js');
var $osf = require('js/osfHelpers');
require('ace-noconflict');
require('ace-mode-markdown');
require('ace-ext-language_tools');
require('addons/wiki/static/ace-markdown-snippets.js');
var Markdown = require('pagedown-ace-converter');
Markdown.getSanitizingConverter = require('pagedown-ace-sanitizer').getSanitizingConverter;
require('imports?Markdown=pagedown-ace-converter!pagedown-ace-editor');


var util = require('./util.js');

var FileEditor = {
    controller: function(contentUrl, shareWSUrl, editorMeta, triggerReload) {
        var self = this;
        self.url = contentUrl;
        self.loaded = false;
        self.initialText = '';
        self.editor = undefined;
        self.editorMeta = editorMeta;
        self.triggerReload = triggerReload;
        self.changed = m.prop(false);

        self.observables = {
            status: m.prop('connecting'),
            activeUsers: m.prop([])
        };

//        self.throttledStatus = m.prop(self.observables.status());


        $osf.throttle(self.observables.status(), 4000, {leading: false});

//        self.throttledUpdateStatus = $osf.throttle(self.updateStatus, 4000, {leading: false});
//
//        self.observables.status.subscribe(function (newValue) {
//            if (newValue !== 'connecting') {
//                self.updateStatus();
//            }
//            self.throttledUpdateStatus();
//        });
//
//        self.updateStatus = function() {
//            self.throttledStatus(self.status());
//        };


        self.bindAce = function(element, isInitialized, context) {
            if (isInitialized) return;
            self.editor = ace.edit(element.id);
            self.editor.setValue(self.initialText);
            self.editor.on('change', self.onChanged);
            var ShareJSDoc = require('js/pages/ShareJSDocFile.js');
            new ShareJSDoc(shareWSUrl, self.editorMeta, self.editor, self.observables);
        };

        self.reloadFile = function() {
            self.loaded = false;
            $.ajax({
                type: 'GET',
                url: self.url,
                beforeSend: $osf.setXHRAuthorization
            }).done(function (response) {
                m.startComputation();
                self.loaded = true;
                self.initialText = response;
                if (self.editor) {
                    self.editor.setValue(self.initialText);
                }
                m.endComputation();
            }).fail(function (xhr, textStatus, error) {
                $osf.growl('Error','The file content could not be loaded.');
                Raven.captureMessage('Could not GET file contents.', {
                    url: self.url,
                    textStatus: textStatus,
                    error: error
                });
            });
        };

        self.saveChanges = function() {
            var request = $.ajax({
                type: 'PUT',
                url: self.url,
                data: self.editor.getValue(),
                beforeSend: $osf.setXHRAuthorization
            }).done(function () {
                self.triggerReload();
                self.initialText = self.editor.getValue();
            }).fail(function(error) {
                self.editor.setValue(self.initialText);
                $osf.growl('Error', 'The file could not be updated.');
                Raven.captureMessage('Could not PUT file content.', {
                    error: error,
                    url: self.url,
                });
            });
        };

        self.revertChanges = function() {
            self.reloadFile();
        };

        self.onChanged = function(e) {
            //To avoid extra typing
            var file1 = self.initialText;
            var file2 = !self.editor ? '' : self.editor.getValue();

            var clean1 = typeof file1 === 'string' ?
                file1.replace(/(\r\n|\n|\r)/gm, '\n') : '';
            var clean2 = typeof file2 === 'string' ?
                file2.replace(/(\r\n|\n|\r)/gm, '\n') : '';

            self.changed(clean1 !== clean2);
        };

        self.reloadFile();
    },
    view: function(ctrl) {
        if (!ctrl.loaded) return util.Spinner;

        return m('.editor-pane', [
            m('.wmd-input.wiki-editor#editor', {config: ctrl.bindAce}),
            m('.osf-panel-footer', [
                m('.col-xs-12', [
                    m('.pull-right', [
                        // m('button.btn.btn-danger', {onclick: ctrl.revertChanges, disabled: ctrl.changed() ? '' : 'disabled'}, 'Revert'),
                        // m('button.btn.btn-success', {onclick: ctrl.saveChanges, disabled: ctrl.changed() ? '' : 'disabled'}, 'Save')
                        m('button.btn.btn-danger', {onclick: ctrl.revertChanges}, 'Revert'),
                        m('button.btn.btn-success', {onclick: ctrl.saveChanges}, 'Save')
                    ])
                ])
            ])
        ]);

    }
};

module.exports = FileEditor;

@@ -979,78 +979,8 @@
 %7D;%0A%0A
-//        self.throttledStatus = m.prop(self.observables.status());%0A%0A%0A
     
@@ -1054,446 +1054,8 @@
 );%0A%0A
-//        self.throttledUpdateStatus = $osf.throttle(self.updateStatus, 4000, %7Bleading: false%7D);%0A//%0A//        self.observables.status.subscribe(function (newValue) %7B%0A//            if (newValue !== 'connecting') %7B%0A//                self.updateStatus();%0A//            %7D%0A//            self.throttledUpdateStatus();%0A//        %7D);%0A//%0A//        self.updateStatus = function() %7B%0A//            self.throttledStatus(self.status());%0A//        %7D;%0A%0A%0A
     
@@ -3130,35 +3130,56 @@
        self.
-reloadFile(
+editor.setValue(self.initialText
 );%0A        %7D
@@ -3935,19 +3935,53 @@
 -xs-12',
+ %7Bstyle:%7B'padding-right': '0px'%7D%7D,
  %5B%0A
-
         
@@ -4015,284 +4015,8 @@
 , %5B%0A
-                        // m('button.btn.btn-danger', %7Bonclick: ctrl.revertChanges, disabled: ctrl.changed() ? '' : 'disabled'%7D, 'Revert'),%0A                        // m('button.btn.btn-success', %7Bonclick: ctrl.saveChanges, disabled: ctrl.changed() ? '' : 'disabled'%7D, 'Save')%0A
     
@@ -4086,24 +4086,55 @@
 evertChanges
+, style:%7B'margin-right': '5px'%7D
 %7D, 'Revert')

Fix revert/save buttons, reset editor text when revert is clicked.