/**
 * Created by rburson on 5/30/16.
 */

import * as React from 'react'
import {
    CvState,
    CvProps,
    CvBaseMixin,
    CvMessagePane,
    CvContext,
    CvMessage,
    CvMessageType,
    CvMessagePaneCallback
} from 'catreact'

import {DialogException, Log, UserMessage} from 'catavolt-sdk'

export interface CvMessagePanelState extends CvState {
}

export interface CvMessagePanelProps extends CvProps {
}

/*
 ***************************************************
 * Render a Message
 ***************************************************
 */
export var CvMessagePanel = React.createClass<CvMessagePanelProps, CvMessagePanelState>({


    mixins: [CvBaseMixin],

    render: function () {

        
        return <CvMessagePane messageRenderer={(cvContext:CvContext, message:CvMessage, callback:CvMessagePaneCallback)=>{

             toastr.options.onHidden = function(){
                 callback.clear();
             }
             if(message.type === CvMessageType.ERROR) {
                 if(message.messageObj && message.messageObj instanceof DialogException) {
                    const dialogException:DialogException = message.messageObj as DialogException;
                    const text = this._createUserMessage(dialogException);
                    toastr.error(text, dialogException.title, {timeOut: 10000, extendedTimeOut: 3000, closeButton:true,
                     showMethod:'slideDown', hideMethod:'slideUp',
                     progressBar:true, preventDuplicates:true});
                 } else {
                     toastr.error(message.message + ' : ' + Log.formatRecString(message.messageObj), 'ERROR', {timeOut: 10000, extendedTimeOut: 3000, closeButton:true,
                         showMethod:'slideDown', hideMethod:'slideUp',
                         progressBar:true, preventDuplicates:true});
                 }
                 Log.error(message.message);
                 Log.error(message.messageObj);
             } else {
                toastr.info(message.message, '', {timeOut: 10000, extendedTimeOut: 3000, closeButton:true,
                 showMethod:'slideDown', hideMethod:'slideUp',
                 progressBar:true, preventDuplicates:true});
             }
             return null;
        }}/>
    },

    _createUserMessage: function(dialogException:DialogException) {
        let text = dialogException.message || dialogException.name || 'An Error Occurred';
        if(dialogException.userMessages && dialogException.userMessages.length > 0) {
            dialogException.userMessages.forEach((userMessage:UserMessage)=>{
                text += '<br><strong>' + userMessage.message + '</strong>';
            });
        }
        return text;
    }

});