/*
 * Copyright 2007-2013 Charles du Jeu - Abstrium SAS <team (at) pyd.io>
 * This file is part of Pydio.
 *
 * Pydio is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Pydio is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with Pydio.  If not, see <http://www.gnu.org/licenses/>.
 *
 * The latest code can be found at <http://pyd.io/>.
 */
"use strict";

(function (global) {

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

        propTypes: {
            user: React.PropTypes.instanceOf(PydioUsers.User)
        },
        render: function render() {
            var userObject = this.props.user;
            return React.createElement(
                "div",
                { className: "user-badge user-type-" + (userObject.getTemporary() ? "tmp_user" : "user") },
                React.createElement("span", { className: "avatar icon-" + (userObject.getTemporary() ? "envelope" : "user") }),
                React.createElement(
                    "span",
                    { className: "user-badge-label" },
                    userObject.getExtendedLabel() || userObject.getLabel()
                )
            );
        }
    });

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

        propTypes: {
            user: React.PropTypes.instanceOf(PydioUsers.User),
            onRemove: React.PropTypes.func
        },
        remove: function remove() {
            this.props.onRemove(this.props.user.getId());
        },
        toggleRemove: function toggleRemove() {
            var current = this.state && this.state.remove;
            this.setState({ remove: !current });
        },
        render: function render() {
            var icon,
                className = 'pydio-mailer-user ' + 'user-type-' + (this.props.user.getTemporary() ? "email" : "user");
            var clik = function clik() {};
            if (this.state && this.state.remove) {
                clik = this.remove;
                icon = React.createElement("span", { className: "avatar mdi mdi-close" });
                className += ' remove';
            } else {
                icon = React.createElement("span", { className: "avatar icon-" + (this.props.user.getTemporary() ? "envelope" : "user") });
            }
            return React.createElement(
                "div",
                { className: className, onMouseOver: this.toggleRemove, onMouseOut: this.toggleRemove, onClick: clik },
                icon,
                this.props.user.getLabel()
            );
        }
    });

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

        propTypes: {
            message: React.PropTypes.string.isRequired,
            subject: React.PropTypes.string.isRequired,
            link: React.PropTypes.string,
            onDismiss: React.PropTypes.func,
            className: React.PropTypes.string,
            overlay: React.PropTypes.bool,
            users: React.PropTypes.object,
            panelTitle: React.PropTypes.string
        },

        getInitialState: function getInitialState() {
            return {
                users: this.props.users || {},
                subject: this.props.subject,
                message: this.props.message,
                errorMessage: null
            };
        },

        componentDidMount: function componentDidMount() {
            var res = new ResourcesManager();
            res.loadCSSResource("plugins/core.mailer/css/PydioMailer.css");
        },

        updateSubject: function updateSubject(event) {
            this.setState({ subject: event.currentTarget.getValue() });
        },

        updateMessage: function updateMessage(event) {
            this.setState({ message: event.currentTarget.getValue() });
        },

        addUser: function addUser(userId, userLabel, type, userObject) {
            var users = this.state.users;
            users[userId] = userObject;
            this.setState({ users: users, errorMessage: null });
        },

        removeUser: function removeUser(userId) {
            delete this.state.users[userId];
            this.setState({ users: this.state.users });
        },

        getMessage: function getMessage(messageId) {
            var nameSpace = arguments.length <= 1 || arguments[1] === undefined ? undefined : arguments[1];

            try {
                if (nameSpace === undefined) nameSpace = 'core.mailer';
                if (nameSpace) nameSpace += ".";
                return global.pydio.MessageHash[nameSpace + messageId];
            } catch (e) {
                return messageId;
            }
        },

        postEmail: function postEmail() {
            if (!Object.keys(this.state.users).length) {
                this.setState({ errorMessage: 'Please pick a user or a mail address' });
                return;
            }
            var params = {
                get_action: "send_mail",
                'emails[]': Object.keys(this.state.users),
                subject: this.state.subject,
                message: this.state.message
            };
            if (this.props.link) {
                params['link'] = this.props.link;
            }
            var client = PydioApi.getClient();
            client.request(params, (function (transport) {
                var res = client.parseXmlMessage(transport.responseXML);
                if (res !== false) {
                    this.props.onDismiss();
                }
            }).bind(this));
        },

        usersLoaderRenderSuggestion: function usersLoaderRenderSuggestion(userObject) {
            return React.createElement(DestBadge, { user: userObject });
        },

        render: function render() {
            var className = [this.props.className, "react-mailer", "react-mui-context", "reset-pydio-forms"].join(" ");
            var users = Object.keys(this.state.users).map((function (uId) {
                return React.createElement(UserEntry, { key: uId, user: this.state.users[uId], onRemove: this.removeUser });
            }).bind(this));
            if (this.state.errorMessage) {
                var errorDiv = React.createElement(
                    "div",
                    { className: "error" },
                    this.state.errorMessage
                );
            }
            var content = React.createElement(
                "div",
                { className: className },
                React.createElement(
                    "h3",
                    null,
                    this.props.panelTitle
                ),
                errorDiv,
                React.createElement(
                    "div",
                    { className: "users-block" },
                    React.createElement(UsersCompleter.Input, {
                        fieldLabel: this.getMessage('8'),
                        usersOnly: true,
                        existingOnly: true,
                        freeValueAllowed: true,
                        onValueSelected: this.addUser,
                        excludes: Object.keys(this.state.users),
                        renderSuggestion: this.usersLoaderRenderSuggestion
                    }),
                    React.createElement(
                        "div",
                        { className: "pydio-mailer-users" },
                        users
                    )
                ),
                React.createElement(ReactMUI.TextField, { floatingLabelText: this.getMessage('6'), value: this.state.subject, onChange: this.updateSubject }),
                React.createElement(ReactMUI.TextField, { floatingLabelText: this.getMessage('7'), value: this.state.message, multiLine: true, onChange: this.updateMessage }),
                React.createElement(
                    "div",
                    { style: { textAlign: 'right' } },
                    React.createElement(ReactMUI.FlatButton, { label: this.getMessage('54', ''), onClick: this.props.onDismiss }),
                    React.createElement(ReactMUI.FlatButton, { primary: true, label: this.getMessage('77', ''), onClick: this.postEmail })
                )
            );
            if (this.props.overlay) {
                return React.createElement(
                    "div",
                    { className: "react-mailer-overlay" },
                    content
                );
            } else {
                return { content: content };
            }
        }
    });

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

        render: function render() {
            return React.createElement(
                "div",
                null,
                "Preferences Panel"
            );
        }
    });

    var PydioMailer = global.PydioMailer || {};
    PydioMailer.Pane = Mailer;
    PydioMailer.PreferencesPanel = Preferences;
    global.PydioMailer = PydioMailer;
})(window);
