/**
 * Created by rburson on 1/15/16.
 */

import * as React from 'react'
import {CvState, CvProps, CvBaseMixin, CvResource} from 'catreact'

export interface CvHtmlResourceProps extends CvProps {
    className?:string;
    style?:{},
    type?:string;
    fallbackImageUrl?:string,
    resourceName?:string
    resourceUrl?:string;
}

export var CvHtmlResource = React.createClass<CvHtmlResourceProps, CvState>({

    mixins: [CvBaseMixin],

    getDefaultProps: function () {
        return {
            type: 'image',
            resourceName: null,
            resourceUrl: null,
            className: null,
            fallbackImageUrl: 'http://cdn.churchm.ag/wp-content/uploads/2013/06/404-Space-Invaders.png',
            style: null
        }
    },

    render: function () {
       
        return <CvResource resourceName={this.props.resourceName}
                           resourceUrl={this.props.resourceUrl}
                           resourceRenderer={(resourceUrl)=>{
                           
                                if (resourceUrl && this.props.type === 'image') {
                                    return <img style={this.props.style} className={this.props.className} src={resourceUrl}
                                                onError={this._loadPlaceholder}/>
                                } else {
                                    return null;
                                }
                                
                           }}/>
    },

    _loadPlaceholder: function (e) {
        e.preventDefault();
        e.target.src = this.props.fallbackImageUrl;
    },

});