/** @jsx React.DOM */

var Addresses = React.createClass({
    render: function() {
        var addrs = this.props.values || null;
        var value;
        if (addrs == null) {
            return (<span></span>);
        } else if (Array.isArray(addrs)) {
            value = addrs.map(function(t) { return t.Address; }).join(", ");
        } else {
            value = addrs.Address;
        }
        return (<p className="email-content-subtitle">{this.props.headerName}: <a>{value}</a></p>)
    }
});

var MainView = React.createClass({
    getInitialState: function() {
        return {
            body: ""
        };
    },

    componentWillReceiveProps: function(nextProps) {
        this.setMessageHash(nextProps.message.Hash);
    },

    componentDidMount: function() {
        this.setMessageHash(this.props.message.Hash);
    },

    setMessageHash: function(hash) {
        $.get("/raw/" + hash , function(data) {
            var body = data.substring(data.indexOf('\n\n')+2);
            this.setState({body: body});
        }.bind(this));
    },

    render: function() {
        // TODO:
        // - trim 'Re:' from messages and group/thread them.
        var m = this.props.message;
        var tos = (m.To||[]).map(function(t) { return t.Address; }).join(', ');
        var ccs = (m.Cc||[]).map(function(t) { return t.Address; }).join(', ');
        return (
<div id="main" className="pure-u-1">
    <div className="email-content">
        <div className="email-content-header pure-g">
            <div className="pure-u-1">
                <h1 className="email-content-title">{m.Subject}</h1>
                <Addresses headerName="From" values={m.From}/>
                <Addresses headerName="To" values={m.To}/>
                <Addresses headerName="Cc" values={m.Cc}/>
                <p className="email-content-subtitle">Date: {m.Date.toLocaleString()}</p>
                <p className="email-content-subtitle">X-Xinu-Hash: {m.Hash}</p>
            </div>

            <div className="email-content-controls pure-u-1">
                <button className="secondary-button pure-button">Reply</button>
                <button className="secondary-button pure-button">Forward</button>
                <a href={"/raw/"+m.Hash} className="secondary-button pure-button">Original</a>
            </div>
        </div>

        <div className="email-content-body"><pre>{this.state.body}</pre></div>
    </div>
</div>
);
  }
});
