Com.Frog.Utils.require(
    '//package/widgets/C4D3C1742001B2ADFB60FF53484E0D0A403B43FCB7BC961F/assets/styles/main.css',
    '//package/widgets/C4D3C1742001B2ADFB60FF53484E0D0A403B43FCB7BC961F/assets/views/main.ejs',
    '//package/widgets/C4D3C1742001B2ADFB60FF53484E0D0A403B43FCB7BC961F/assets/views/embed_site.ejs',
    '//package/widgets/C4D3C1742001B2ADFB60FF53484E0D0A403B43FCB7BC961F/models/models.js',
    '//package/widgets/C4D3C1742001B2ADFB60FF53484E0D0A403B43FCB7BC961F/models/eportfolio_models.js',
    '//package/widgets/C4D3C1742001B2ADFB60FF53484E0D0A403B43FCB7BC961F/widget.ejs'
).then(function() {
    Com.Frog.Controllers.Widget.extend('Widget.ePortfolioEmbed', {
    }, {
        prefs: {
            height: {
                type: 'number',
                label: 'Height',
                defaultValue: '500',
                showUnits: 'px',
                inline: true
            },
            collectionName: {
                type: 'text',
                label: "Collection name  (This widget will embed first ePortfolio found for the logged-in user.  If the user has more than one, use the Collection's name to identify the correct ePortfolio)",
                defaultValue: ''
            },
            safe_mode: {
                type: 'toggle',
                attr: 'value',
                label: 'Safe Mode (Default: FALSE)',
                defaultValue: false,
                options: {
                    'Off': false,
                    'On': true
                }
            },
            sm_val: {
                type: 'hidden',
                label: '',
                defaultValue: ''
            }
        },

        packageID: 'C4D3C1742001B2ADFB60FF53484E0D0A403B43FCB7BC961F',
        /**
         * Constructor. Runs when the widget is first loaded.
         *
         * @method init
         */
        init: function() {
            if (!this.options.userIsAuthenticated) {
                return false;
            }

            // If not logged in as FrogTrade or FrogSuper then safe_mode gets deleted
            // sm_val is a hidden value that is set to safe_mode on init
            // Later if we don't have safe_mode we can still use sm_val that is saved.
            this.prefs.sm_val.value = this.prefs.safe_mode.value;
            if(this.options.user.profile.type !== "superuser"){
                delete this.prefs.safe_mode;
            }
        },
        
        render: function() {
                if (!Frog.isLoggedIn) {
                    this.renderEmpty();
                    return;
                }
                this.getData();
            },

            getData: function () {
                var order = {},
                    method = 'getMyEportfolios';

                if (this.options.user.profile.type === 'parent') {
                    method = 'getMyChildsEportfolios';
                }

                order[this.options.sortKey] = this.options.sortDirection;
                Widget.Models.Eportfolio[method]({
                    'order': order
                }).done(function(sites) {
                    if (sites.length) {
                        var embedSite;
                        if (this.prefs.collectionName.value !== '') {
                            $.each(sites, function(index,site) {
                                if (~site.name.toLowerCase().indexOf( this.prefs.collectionName.value.toLowerCase() )) {
                                    embedSite = site;
                                }
                            }.bind(this));
                        } else {
                            embedSite = sites[0];
                        }
                        if (embedSite != undefined) {
                            this.parseParams(embedSite);
                            this.renderSite(embedSite);  
                        } else {
                            this.renderEmpty();
                        }
                    } else {
                        this.renderEmpty();
                    }
                }.bind(this));
            },

            renderEmpty: function() {
               this.element.html(this.view('main.ejs'));
            },

            renderSite: function (embedSite) {
                this.element.html(
                     this.view('embed_site.ejs', this.params)
                );
                            
                if (this.params.state !== 'edit' && this.params.site_uuid) {
                    // Set to true as that was the default value before the change
                    var safe_mode = false;

                    // If logged in as super, use we can use safe_mode (which can be changed)
                    if (this.prefs.safe_mode) {
                        safe_mode = !!this.prefs.safe_mode.value;

                        // Else use sm_val, the set value on init. (can't be changed)
                    } else if (this.prefs.sm_val) {
                        safe_mode = !!this.prefs.sm_val.value;
                    }

                    this.element.trigger('os.internal.launchEmbeddedApp', {
                        app_name: 'sites',
                        app_container: this.element.find('.embedsite-container'),
                        app_width: this.element.width(),
                        app_height: this.element.height(),
                        app_data: {
                           data: {
                                site: embedSite.uuid,
                                safe_mode: safe_mode,
                                mode: 'default',
                                is_embedded: true
                            }
                        }
                    });

                    this.element.find('.embedsite-container').css('height', parseInt(this.prefs.height.value) || this.prefs.height.defaultValue);
               }

            },
            parseParams: function(embedSite) {

                this.params = {
                    site_uuid: embedSite.uuid,
                    site_name: embedSite.name,
                    current_site_uuid: this.options.site_uuid,
                    state: this.state,
                    is_embedded: this.element.closest('.app_dialog').hasClass('app_embedded')
                };
            },

            'mysorter.sort': function(el, ev, data) {
                this.options.sortKey = data.key;
                this.options.sortDirection = data.direction;
                this.render();
            },

            '[data-action="open_site"] click': function(el, ev) {
                this.trigger('os.app.siteviewer', {site: $(el).model().uuid});
            },

            /**
             * Triggered when this widget enters edit mode.
             */
            'widget.edit': function(el, ev) {
                this.element.html(
                    this.view('./widget.ejs')
                );
            },

            /**
             * Triggered when this widget exits edit mode, and when the widget is
             * first loaded.
             */
            'widget.live': function(el, ev) {
                this.render();
            }
        });
    });


