"use strict";

(function (global) {

    var HomeWorkspaceLegendPanel = React.createClass({
        displayName: "HomeWorkspaceLegendPanel",

        setWorkspace: function setWorkspace(ws) {
            this.refs.legend.setWorkspace(ws);
        },
        render: function render() {
            return React.createElement(
                "div",
                { id: "home_center_panel" },
                React.createElement(
                    "div",
                    { id: "logo_div" },
                    React.createElement(ConfigLogo, { pydio: this.props.pydio, pluginName: "gui.ajax", pluginParameter: "CUSTOM_DASH_LOGO" })
                ),
                React.createElement(HomeWorkspaceLegend, {
                    ref: "legend",
                    onShowLegend: this.props.onShowLegend,
                    onHideLegend: this.props.onHideLegend,
                    onOpenLink: this.props.onOpenLink })
            );
        }
    });

    var ConfigLogo = React.createClass({
        displayName: "ConfigLogo",

        render: function render() {
            var logo = this.props.pydio.Registry.getPluginConfigs(this.props.pluginName).get(this.props.pluginParameter);
            var url;
            if (!logo) {
                logo = this.props.pydio.Registry.getDefaultImageFromParameters(this.props.pluginName, this.props.pluginParameter);
            }
            if (logo) {
                if (logo.indexOf('plugins/') === 0) {
                    url = logo;
                } else {
                    url = this.props.pydio.Parameters.get('ajxpServerAccess') + "&get_action=get_global_binary_param&binary_id=" + logo;
                }
            }
            return React.createElement("img", { src: url });
        }
    });

    var DlAppElement = React.createClass({
        displayName: "DlAppElement",

        propTypes: {
            id: React.PropTypes.string,
            configs: React.PropTypes.object,
            configHref: React.PropTypes.string,
            containerClassName: React.PropTypes.string,
            iconClassName: React.PropTypes.string,
            messageId: React.PropTypes.string,
            tooltipId: React.PropTypes.string
        },

        render: function render() {
            return React.createElement(
                ReactPydio.LabelWithTip,
                { className: "dl_tooltip_container", tooltip: MessageHash[this.props.tooltipId] },
                React.createElement(
                    "div",
                    { id: this.props.id },
                    React.createElement("a", { href: this.props.configs.get(this.props.configHref), target: "_blank", className: this.props.containerClassName }),
                    React.createElement("a", { href: this.props.configs.get(this.props.configHref), target: "_blank", className: this.props.iconClassName }),
                    React.createElement(
                        "div",
                        { style: { color: 'white' } },
                        MessageHash[this.props.messageId]
                    )
                )
            );
        }
    });

    var VideoCard = React.createClass({
        displayName: "VideoCard",

        propTypes: {
            youtubeId: React.PropTypes.string,
            contentMessageId: React.PropTypes.string,
            launchVideo: React.PropTypes.func
        },

        launchVideo: function launchVideo() {
            this.props.launchVideo("//www.youtube.com/embed/" + this.props.youtubeId + "?list=PLxzQJCqzktEYnIChsR5h3idjAxgBssnt5&autoplay=1");
        },

        render: function render() {
            var htmlMessage = function htmlMessage(id) {
                return { __html: MessageHash[id] };
            };
            return React.createElement(
                "div",
                { className: "video-card" },
                React.createElement(
                    "div",
                    { className: "tutorial_legend" },
                    React.createElement("div", { className: "tutorial_video_thumb", style: { backgroundImage: 'url("https://img.youtube.com/vi/' + this.props.youtubeId + '/0.jpg")' } }),
                    React.createElement(
                        "div",
                        { className: "tutorial_content" },
                        React.createElement("span", { dangerouslySetInnerHTML: htmlMessage(this.props.contentMessageId) })
                    ),
                    React.createElement(
                        "div",
                        { className: "tutorial_load_button", onClick: this.launchVideo },
                        React.createElement("i", { className: "icon-youtube-play" }),
                        " Play Video"
                    )
                )
            );
        }
    });

    var VideoPlayer = React.createClass({
        displayName: "VideoPlayer",

        propTypes: {
            videoSrc: React.PropTypes.string,
            closePlayer: React.PropTypes.func
        },

        render: function render() {
            return React.createElement(
                "div",
                { className: "video-player", style: { position: 'absolute', top: 0, left: 0, right: 0, bottom: 0, zIndex: 200000 } },
                React.createElement("div", { className: "overlay", style: { position: 'absolute', top: 0, left: 0, right: 0, bottom: 0, backgroundColor: 'black', opacity: 0.4 } }),
                React.createElement("iframe", { src: this.props.videoSrc, style: { position: 'absolute', top: '10%', left: '10%', width: '80%', height: '80%', border: '0' } }),
                React.createElement("a", { className: "mdi mdi-close", style: { position: 'absolute', right: '8%', top: '7%', color: 'white', textDecoration: 'none' }, onClick: this.props.closePlayer })
            );
        }
    });

    var TutorialPane = React.createClass({
        displayName: "TutorialPane",

        propTypes: {
            closePane: React.PropTypes.func,
            open: React.PropTypes.bool
        },

        closePane: function closePane() {
            this.props.closePane();
        },

        closePlayer: function closePlayer() {
            this.setState({ player: null });
        },

        launchVideo: function launchVideo(videoSrc) {
            this.setState({ player: videoSrc });
        },

        render: function render() {
            var htmlMessage = function htmlMessage(id) {
                return { __html: MessageHash[id] };
            };

            var videoPlayer;
            if (this.state && this.state.player) {
                videoPlayer = React.createElement(VideoPlayer, { videoSrc: this.state.player, closePlayer: this.closePlayer });
            }

            return React.createElement(
                "span",
                null,
                videoPlayer,
                React.createElement(
                    "div",
                    { id: "videos_pane", className: this.props.open ? "open" : "closed" },
                    React.createElement("div", { onClick: this.closePane, className: "mdi mdi-close" }),
                    React.createElement(
                        "div",
                        { className: "tutorial_title" },
                        MessageHash['user_home.56']
                    ),
                    React.createElement(
                        "div",
                        { className: "videoCards" },
                        React.createElement(VideoCard, {
                            launchVideo: this.launchVideo,
                            youtubeId: "C6L_9QT0lDE",
                            contentMessageId: "user_home.62"
                        }),
                        React.createElement(VideoCard, {
                            launchVideo: this.launchVideo,
                            youtubeId: "ZuVKsIa4XdU",
                            contentMessageId: "user_home.63"
                        }),
                        React.createElement(VideoCard, {
                            launchVideo: this.launchVideo,
                            youtubeId: "MEHCN64RoTY",
                            contentMessageId: "user_home.64"
                        }),
                        React.createElement(VideoCard, {
                            launchVideo: this.launchVideo,
                            youtubeId: "ot2Nq-RAnYE",
                            contentMessageId: "user_home.66"
                        })
                    ),
                    React.createElement(
                        "div",
                        { className: "tutorial_more_videos_cont" },
                        React.createElement(
                            "a",
                            { className: "tutorial_more_videos_button", href: "https://www.youtube.com/channel/UCNEMnabbk64csjA_qolXvPA", target: "_blank" },
                            React.createElement("i", { className: "icon-youtube-play" }),
                            React.createElement("span", { dangerouslySetInnerHTML: htmlMessage('user_home.65') })
                        )
                    )
                )
            );
        }

    });

    var HomeWorkspaceUserCartridge = React.createClass({
        displayName: "HomeWorkspaceUserCartridge",

        clickDisconnect: function clickDisconnect() {
            this.props.controller.fireAction("logout");
        },

        clickConnect: function clickConnect() {
            this.props.controller.fireAction("login");
        },

        showGettingStarted: function showGettingStarted() {
            //this.props.controller.fireAction("open_tutorial_pane");
            this.setState({ showGettingStarted: true });
        },

        getInitialState: function getInitialState() {
            return { showGettingStarted: false };
        },

        render: function render() {
            var userLabel = this.props.user.getPreference("USER_DISPLAY_NAME") || this.props.user.id;
            var loginLink = '';
            if (this.props.controller.getActionByName("logout") && this.props.user.id != "guest") {
                var parts = MessageHash["user_home.67"].replace('%s', userLabel).split("%logout");
                loginLink = React.createElement(
                    "small",
                    null,
                    parts[0],
                    React.createElement(
                        "span",
                        { id: "disconnect_link", onClick: this.clickDisconnect },
                        React.createElement(
                            "a",
                            null,
                            this.props.controller.getActionByName("logout").options.text.toLowerCase()
                        )
                    ),
                    parts[1]
                );
            } else if (this.props.user.id == "guest" && this.props.controller.getActionByName("login")) {
                loginLink = React.createElement(
                    "small",
                    null,
                    "You can ",
                    React.createElement(
                        "a",
                        { id: "disconnect_link", onClick: this.clickConnect },
                        "login"
                    ),
                    " if you are not guest."
                );
            }

            var gettingStartedBlock = '';
            var gettingStartedPanel;
            if (this.props.enableGettingStarted) {
                var dgs = function dgs() {
                    return { __html: MessageHash["user_home.55"] };
                };
                gettingStartedBlock = React.createElement(
                    "small",
                    null,
                    " ",
                    React.createElement("span", { onClick: this.showGettingStarted, dangerouslySetInnerHTML: dgs() })
                );
                var close = (function () {
                    this.setState({ showGettingStarted: false });
                }).bind(this);
                gettingStartedPanel = React.createElement(TutorialPane, { closePane: close, open: this.state.showGettingStarted });
            }

            return React.createElement(
                "div",
                { id: "welcome" },
                gettingStartedPanel,
                MessageHash['user_home.40'].replace('%s', userLabel),
                React.createElement(
                    "p",
                    null,
                    loginLink,
                    gettingStartedBlock
                )
            );
        }

    });

    var DlAppsPanel = React.createClass({
        displayName: "DlAppsPanel",

        render: function render() {
            var configs = pydio.getPluginConfigs('access.ajxp_home');
            var mobileBlocks = [],
                syncBlocks = [];
            if (configs.get('URL_APP_IOSAPPSTORE')) {
                mobileBlocks.push(React.createElement(DlAppElement, {
                    id: "dl_pydio_ios",
                    key: "dl_pydio_ios",
                    configs: configs,
                    configHref: "URL_APP_IOSAPPSTORE",
                    containerClassName: "icon-tablet",
                    iconClassName: "icon-apple",
                    messageId: "user_home.59",
                    tooltipId: "user_home.70"
                }));
            }
            if (configs.get('URL_APP_ANDROID')) {
                mobileBlocks.push(React.createElement(DlAppElement, {
                    id: "dl_pydio_android",
                    key: "dl_pydio_android",
                    configs: configs,
                    configHref: "URL_APP_ANDROID",
                    containerClassName: "icon-mobile-phone",
                    iconClassName: "icon-android",
                    messageId: "user_home.58",
                    tooltipId: "user_home.71"
                }));
            }
            if (configs.get('URL_APP_SYNC_WIN')) {
                syncBlocks.push(React.createElement(DlAppElement, {
                    id: "dl_pydio_win",
                    key: "dl_pydio_win",
                    configs: configs,
                    configHref: "URL_APP_SYNC_WIN",
                    containerClassName: "icon-laptop",
                    iconClassName: "icon-windows",
                    messageId: "user_home.61",
                    tooltipId: "user_home.68"
                }));
            }
            if (configs.get('URL_APP_SYNC_MAC')) {
                syncBlocks.push(React.createElement(DlAppElement, {
                    id: "dl_pydio_mac",
                    key: "dl_pydio_mac",
                    configs: configs,
                    configHref: "URL_APP_SYNC_MAC",
                    containerClassName: "icon-desktop",
                    iconClassName: "icon-apple",
                    messageId: "user_home.60",
                    tooltipId: "user_home.69"
                }));
            }
            var blocksSep = undefined;
            if (mobileBlocks.length && syncBlocks.length) {
                blocksSep = React.createElement("div", { className: "dl_blocks_sep" });
            }

            return React.createElement(
                "div",
                { id: "tutorial_dl_apps_pane" },
                React.createElement(
                    "div",
                    { id: "dl_pydio_cont", className: "react-mui-context" },
                    syncBlocks,
                    blocksSep,
                    mobileBlocks
                )
            );
        }

    });

    var HomeWorkspaceLegend = React.createClass({
        displayName: "HomeWorkspaceLegend",

        getInitialState: function getInitialState() {
            return { workspace: null };
        },
        enterWorkspace: function enterWorkspace(event) {
            this.props.onOpenLink(event, this.state.workspace, this.refs.save_ws_choice.getDOMNode().checked);
        },
        componentWillUnmount: function componentWillUnmount() {
            if (window['homeWorkspaceTimer']) {
                window.clearTimeout(window['homeWorkspaceTimer']);
            }
        },
        setWorkspace: function setWorkspace(ws) {
            if (!this._internalCache) {
                this._internalCache = new Map();
                this._repoInfosLoading = new Map();
            }
            this._internalState = ws;
            if (!ws) {
                bufferCallback('homeWorkspaceTimer', 7000, (function () {
                    this.setState({ workspace: null });
                    this.props.onHideLegend();
                }).bind(this));
                return;
            }
            // check the cache and re-render?
            var repoId = ws.getId();
            if (!this._repoInfosLoading.get(repoId) && !this._internalCache.get(repoId)) {
                this.props.onShowLegend(ws);
                this._repoInfosLoading.set(repoId, 'loading');
                PydioApi.getClient().request({
                    get_action: 'load_repository_info',
                    tmp_repository_id: repoId,
                    collect: 'true'
                }, (function (transport) {
                    this._repoInfosLoading["delete"](repoId);
                    if (transport.responseJSON) {
                        var data = transport.responseJSON;
                        this._internalCache.set(repoId, data);
                        if (this._internalState == ws) {
                            this.setState({ workspace: ws, data: data });
                        }
                    }
                }).bind(this));
            } else if (this._internalCache.get(repoId)) {
                this.props.onShowLegend(ws);
                this.setState({ workspace: ws, data: this._internalCache.get(repoId) });
            }
        },
        render: function render() {
            var _this = this;

            if (!this.state.workspace) {
                //return <div id="ws_legend" className="empty_ws_legend"></div>;
                return React.createElement(DlAppsPanel, null);
            }
            var blocks = [];
            var data = this.state.data;
            var usersData = data['core.users'];

            if (usersData && usersData['users'] != undefined && usersData['groups'] != undefined) {
                blocks.push(React.createElement(
                    HomeWorkspaceLegendInfoBlock,
                    { key: "core.users", badgeTitle: MessageHash[527], iconClass: "mdi mdi-account-network" },
                    React.createElement(
                        "div",
                        { className: "table" },
                        (function () {
                            if (usersData['users'] > 0) {
                                return React.createElement(
                                    "div",
                                    null,
                                    React.createElement(
                                        "div",
                                        null,
                                        MessageHash[531]
                                    ),
                                    React.createElement(
                                        "div",
                                        { className: "text-center" },
                                        usersData['users']
                                    )
                                );
                            }
                        })(),
                        (function () {
                            if (usersData['groups'] > 0) {
                                return React.createElement(
                                    "div",
                                    null,
                                    React.createElement(
                                        "div",
                                        null,
                                        MessageHash[532]
                                    ),
                                    React.createElement(
                                        "div",
                                        { className: "text-center" },
                                        usersData['groups']
                                    )
                                );
                            }
                        })()
                    )
                ));
            }
            if (data['access.inbox']) {
                blocks.push(React.createElement(
                    HomeWorkspaceLegendInfoBlock,
                    { key: "core.users", badgeTitle: MessageHash['inbox_driver.2p'], iconClass: "mdi mdi-file-multiple" },
                    React.createElement(
                        "div",
                        { className: "table" },
                        React.createElement(
                            "div",
                            null,
                            React.createElement(
                                "div",
                                null,
                                MessageHash['inbox_driver.16']
                            ),
                            React.createElement(
                                "div",
                                { className: "text-center" },
                                data['access.inbox']['files']
                            )
                        ),
                        (function () {
                            if (_this.state.workspace.getAccessStatus() > 0) {
                                return React.createElement(
                                    "div",
                                    null,
                                    React.createElement(
                                        "div",
                                        null,
                                        MessageHash['inbox_driver.17']
                                    ),
                                    React.createElement(
                                        "div",
                                        { className: "text-center" },
                                        _this.state.workspace.getAccessStatus()
                                    )
                                );
                            }
                        })()
                    )
                ));
            }
            if (data['meta.quota']) {
                blocks.push(React.createElement(
                    HomeWorkspaceLegendInfoBlock,
                    { key: "meta.quota", badgeTitle: MessageHash['meta.quota.4'], iconClass: "icon-dashboard" },
                    React.createElement(
                        "div",
                        { className: "table" },
                        React.createElement(
                            "div",
                            null,
                            React.createElement(
                                "div",
                                null,
                                parseInt(100 * data['meta.quota']['usage'] / data['meta.quota']['total']),
                                "%"
                            ),
                            React.createElement(
                                "div",
                                { className: "text-right" },
                                React.createElement(
                                    "small",
                                    null,
                                    roundSize(data['meta.quota']['total'], MessageHash["byte_unit_symbol"])
                                )
                            )
                        )
                    )
                ));
            }
            if (data['core.notifications'] && data['core.notifications'][0]) {
                blocks.push(React.createElement(
                    HomeWorkspaceLegendInfoBlock,
                    { key: "notifications", badgeTitle: MessageHash[4], iconClass: "mdi mdi-calendar" },
                    React.createElement(
                        "div",
                        { className: "text-center" },
                        data['core.notifications'][0]['short_date']
                    )
                ));
            }

            if (blocks.length == 1) {
                blocks.push(React.createElement("div", { className: "repoInfoBadge", style: { visibility: 'hidden' } }));
            }

            return React.createElement(
                "div",
                { id: "ws_legend" },
                React.createElement(
                    "div",
                    { className: "repoInfoBadge main size-" + blocks.length },
                    React.createElement(
                        "div",
                        { className: "repoInfoBox flexbox" },
                        React.createElement(
                            "div",
                            { className: "repoInfoBody content" },
                            React.createElement(
                                "h4",
                                null,
                                this.state.workspace.getLabel()
                            ),
                            this.state.workspace.getDescription()
                        ),
                        React.createElement(
                            "div",
                            { className: "repoInfoHeader row header" },
                            React.createElement(
                                "span",
                                { className: "repoInfoTitle" },
                                React.createElement(
                                    "span",
                                    { className: "enter_save_choice", style: { lineHeight: '0.5em' } },
                                    React.createElement("input", { type: "checkbox", ref: "save_ws_choice", id: "save_ws_choice" }),
                                    React.createElement(
                                        "label",
                                        { htmlFor: "save_ws_choice" },
                                        MessageHash['user_home.41']
                                    )
                                ),
                                React.createElement(
                                    "a",
                                    { onClick: this.enterWorkspace },
                                    MessageHash['user_home.42']
                                )
                            )
                        )
                    )
                ),
                React.createElement(
                    "div",
                    { className: "repoInfo" },
                    blocks
                )
            );
        }
    });

    var HomeWorkspaceLegendInfoBlock = React.createClass({
        displayName: "HomeWorkspaceLegendInfoBlock",

        render: function render() {
            return React.createElement(
                "div",
                { className: "repoInfoBadge" },
                React.createElement(
                    "div",
                    { className: "repoInfoBox flexbox" },
                    React.createElement(
                        "div",
                        { className: "repoInfoBody row content" },
                        this.props.children
                    ),
                    React.createElement(
                        "div",
                        { className: "repoInfoHeader row header" },
                        React.createElement(
                            "span",
                            { className: "repoInfoTitle" },
                            this.props.badgeTitle
                        ),
                        React.createElement("span", { className: this.props.iconClass })
                    )
                )
            );
        }
    });

    var UserDashboard = React.createClass({
        displayName: "UserDashboard",

        getInitialState: function getInitialState() {
            return {
                workspaces: this.props.pydio.user.getRepositoriesList()
            };
        },

        componentDidMount: function componentDidMount() {
            if (this._timer) global.clearTimeout(this._timer);
            this._timer = global.setTimeout(this.closeNavigation, 3000);

            this._reloadObserver = (function () {

                if (this.isMounted()) {
                    this.setState({
                        workspaces: this.props.pydio.user.getRepositoriesList()
                    });
                }
            }).bind(this);

            this.props.pydio.observe('repository_list_refreshed', this._reloadObserver);
        },

        componentWillUnmount: function componentWillUnmount() {
            if (this._reloadObserver) {
                this.props.pydio.stopObserving('repository_list_refreshed', this._reloadObserver);
            }
        },
        switchToWorkspace: function switchToWorkspace(repoId, save) {
            if (!repoId) return;
            if (save) {
                PydioApi.getClient().request({
                    'PREFERENCES_DEFAULT_START_REPOSITORY': repoId,
                    'get_action': 'custom_data_edit'
                }, (function () {
                    this.props.pydio.user.setPreference('DEFAULT_START_REPOSITORY', repoId, false);
                }).bind(this));
            }
            this.props.pydio.triggerRepositoryChange(repoId);
        },
        onShowLegend: function onShowLegend() {
            // PROTO STUFF!
            $('home_center_panel').addClassName('legend_visible');
        },
        onHideLegend: function onHideLegend() {
            // PROTO STUFF!
            $('home_center_panel').removeClassName('legend_visible');
        },
        onHoverLink: function onHoverLink(event, ws) {
            bufferCallback('hoverWorkspaceTimer', 400, (function () {
                this.refs.legend.setWorkspace(ws);
            }).bind(this));
        },
        onOutLink: function onOutLink(event, ws) {
            this.refs.legend.setWorkspace(null);
        },
        onOpenLink: function onOpenLink(event, ws, save) {
            this.switchToWorkspace(ws.getId(), save);
        },
        render: function render() {
            var simpleClickOpen = this.props.pydio.getPluginConfigs("access.ajxp_home").get("SIMPLE_CLICK_WS_OPEN");
            var enableGettingStarted = this.props.pydio.getPluginConfigs('access.ajxp_home').get("ENABLE_GETTING_STARTED");
            return React.createElement(
                "div",
                { className: "horizontal_layout vertical_fit" },
                React.createElement(
                    "div",
                    { id: "home_left_bar", className: "vertical_layout" },
                    React.createElement(HomeWorkspaceUserCartridge, { style: { minHeight: '94px' },
                        controller: this.props.pydio.getController(),
                        user: this.props.pydio.user,
                        enableGettingStarted: enableGettingStarted
                    }),
                    React.createElement(
                        "div",
                        { id: "workspaces_center", className: "vertical_layout vertical_fit" },
                        React.createElement(LeftNavigation.UserWorkspacesList, {
                            pydio: this.props.pydio,
                            workspaces: this.state.workspaces,
                            onHoverLink: this.onHoverLink,
                            onOutLink: this.onOutLink
                        })
                    )
                ),
                React.createElement(HomeWorkspaceLegendPanel, { ref: "legend",
                    pydio: this.props.pydio,
                    onShowLegend: this.onShowLegend,
                    onHideLegend: this.onHideLegend,
                    onOpenLink: this.onOpenLink
                }),
                this.props.children
            );
        }

    });

    var QRCodeDialogLoader = React.createClass({
        displayName: "QRCodeDialogLoader",

        closeClicked: function closeClicked() {
            this.props.closeAjxpDialog();
        },

        render: function render() {

            var jsonData = {
                "server": global.location.href.split('welcome').shift(),
                "user": global.pydio.user ? global.pydio.user.id : null
            };

            return React.createElement(
                "div",
                null,
                React.createElement(
                    "div",
                    { className: "home-qrCode-desc" },
                    React.createElement(
                        "h4",
                        null,
                        global.pydio.MessageHash['user_home.72']
                    ),
                    React.createElement(
                        "p",
                        null,
                        global.pydio.MessageHash['user_home.74']
                    )
                ),
                React.createElement(
                    "div",
                    { className: "home-qrCode" },
                    React.createElement(ReactQRCode, { value: JSON.stringify(jsonData), size: 256 }),
                    React.createElement(
                        "div",
                        { className: "button-panel" },
                        React.createElement(ReactMUI.FlatButton, { label: "Close", onClick: this.closeClicked })
                    )
                )
            );
        }

    });

    var WelcomeComponents = global.WelcomeComponents || {};
    WelcomeComponents.UserDashboard = UserDashboard;
    WelcomeComponents.TutorialPane = TutorialPane;
    WelcomeComponents.QRCodeDialogLoader = QRCodeDialogLoader;
    global.WelcomeComponents = WelcomeComponents;
})(window);
