import Ember from 'ember';
import AuthConfiguration from 'ember-simple-auth/configuration';
import ApplicationRouteMixin from 'ember-simple-auth/mixins/application-route-mixin';
import ShortcutsRoute from 'ghost-admin/mixins/shortcuts-route';
import ctrlOrCmd from 'ghost-admin/utils/ctrl-or-cmd';
import windowProxy from 'ghost-admin/utils/window-proxy';

const {
    Route,
    inject: {service},
    run
} = Ember;

function K() {
    return this;
}

let shortcuts = {};

shortcuts.esc = {action: 'closeMenus', scope: 'all'};
shortcuts[`${ctrlOrCmd}+s`] = {action: 'save', scope: 'all'};

export default Route.extend(ApplicationRouteMixin, ShortcutsRoute, {
    shortcuts,

    config: service(),
    feature: service(),
    dropdown: service(),
    notifications: service(),

    afterModel(model, transition) {
        this._super(...arguments);

        if (this.get('session.isAuthenticated')) {
            this.set('appLoadTransition', transition);
            transition.send('loadServerNotifications');

            // return the feature loading promise so that we block until settings
            // are loaded in order for synchronous access everywhere
            return this.get('feature').fetch();
        }
    },

    title(tokens) {
        return `${tokens.join(' - ')} - ${this.get('config.blogTitle')}`;
    },

    sessionAuthenticated() {
        if (this.get('session.skipAuthSuccessHandler')) {
            return;
        }

        // standard ESA post-sign-in redirect
        this._super(...arguments);

        // trigger post-sign-in background behaviour
        this.get('session.user').then((user) => {
            this.send('signedIn', user);
        });
    },

    sessionInvalidated() {
        let transition = this.get('appLoadTransition');

        if (transition) {
            transition.send('authorizationFailed');
        } else {
            run.scheduleOnce('routerTransitions', this, function () {
                this.send('authorizationFailed');
            });
        }
    },

    actions: {
        openMobileMenu() {
            this.controller.set('showMobileMenu', true);
        },

        openSettingsMenu() {
            this.controller.set('showSettingsMenu', true);
        },

        closeMenus() {
            this.get('dropdown').closeDropdowns();
            this.controller.setProperties({
                showSettingsMenu: false,
                showMobileMenu: false
            });
        },

        didTransition() {
            this.set('appLoadTransition', null);
            this.send('closeMenus');
        },

        signedIn() {
            this.get('notifications').clearAll();
            this.send('loadServerNotifications', true);
        },

        invalidateSession() {
            this.get('session').invalidate().catch((error) => {
                this.get('notifications').showAlert(error.message, {type: 'error', key: 'session.invalidate.failed'});
            });
        },

        authorizationFailed() {
            windowProxy.replaceLocation(AuthConfiguration.baseURL);
        },

        loadServerNotifications(isDelayed) {
            if (this.get('session.isAuthenticated')) {
                this.get('session.user').then((user) => {
                    if (!user.get('isAuthor') && !user.get('isEditor')) {
                        this.store.findAll('notification', {reload: true}).then((serverNotifications) => {
                            serverNotifications.forEach((notification) => {
                                this.get('notifications').handleNotification(notification, isDelayed);
                            });
                        });
                    }
                });
            }
        },

        toggleMarkdownHelpModal() {
            this.get('controller').toggleProperty('showMarkdownHelpModal');
        },

        // noop default for unhandled save (used from shortcuts)
        save: K
    }
});

@@ -2703,32 +2703,85 @@
 ations', true);%0A
+            this.send('checkForOutdatedDesktopApp');%0A
         %7D,%0A%0A    
@@ -3767,32 +3767,1037 @@
   %7D%0A        %7D,%0A%0A
+        checkForOutdatedDesktopApp() %7B%0A            // Check if the user is running an older version of Ghost Desktop%0A            // that needs to be manually updated%0A            // (yes, the desktop team is deeply ashamed of these lines %F0%9F%98%A2)%0A            let ua = navigator && navigator.userAgent ? navigator.userAgent : null;%0A%0A            if (ua && ua.includes && ua.includes('ghost-desktop')) %7B%0A                let updateCheck = /ghost-desktop%5C/0%5C.((5%5C.0)%7C((4%7C2)%5C.0)%7C((3%5C.)(0%7C1)))/;%0A                let link = '%3Ca href=%22https://dev.ghost.org/ghost-desktop-manual-update%22 target=%22_blank%22%3Eclick here%3C/a%3E';%0A                let msg = %60Your version of Ghost Desktop needs to be manually updated. Please $%7Blink%7D to get started.%60;%0A%0A                if (updateCheck.test(ua)) %7B%0A                    this.get('notifications').showAlert(msg.htmlSafe(), %7B%0A                        type: 'upgrade',%0A                        key: 'desktop.manual.upgrade'%0A                    %7D);%0A                %7D%0A            %7D%0A        %7D,%0A%0A
         toggleMa

Check for Ghost Desktop manual update