import React from 'react';
import {pusherConst} from './PusherConstants.js';
import styles from './header.scss';
import Badge from 'material-ui/Badge';
import NotificationsIcon from 'material-ui/svg-icons/social/notifications';
import IconButton from 'material-ui/IconButton';
import NotificationBar from './NotificationBar/Notification.js';
import * as headerActions from './BellActions';
import {doHttpGet} from '../../UtilitiesFunctions/ajaxUtilities.js';
import {checkDeepEquals, dateFormatter} from '../../UtilitiesFunctions/objectUtilities.js';
import EditAlerts from '../editAlert/EditAlerts';


export default class Bell extends React.Component{

    constructor(props) {
        super(props);
        this.state = {
                      notificationsArray: [],
                      pusherNotificationArray :[],
                      showModal : false,
                      notificationCount: 0,
                      primeNotificationCount: 0,
                      unreadPusherNotificationCount: 0,
                      user:{},
                      tripClosureFields : [{
                        id: 1,
                        Header: 'Trip Code',
                        accessor: 'tripCode'
                    },{
                        id: 2,
                        Header: 'Vehicle No',
                        accessor: 'vehicleNumber',
                    }],

                        tdsFields : [{
                            id: 1,
                            Header: 'Trip Code',
                            accessor: 'tripCode'
                        },{
                            id: 2,
                            Header: 'Vehicle No',
                            accessor: 'vehicleNumber',
                        },{
                            id: 3,
                            Header: 'Departure Time',
                            accessor: 'tdsDepartureTimestamp',
                        }],
                    showEditModal: false,

                    fields : [{
                            id: 1,
                            Header: 'Trip Code',
                            accessor: 'tripCode'
                        },{
                            id: 2,
                            Header: 'Vehicle No',
                            accessor: 'vehicleNumber',
                         }, {
                            id:3,
                            Header: 'Reason',
                            accessor: 'reason'
                        }, {
                            Header: 'Comment',
                            id:4,
                            accessor: 'comment'
                        },{
                            Header: 'Raised By',
                            id:5,
                            accessor: 'raisedBy'
                         }]

                    }
     }


    componentDidMount(){
        var user = this.props.user;
        let self = this;
        console.log('Bell this', this);
        if(this.props.user){
        self.setState({user: self.props.user});
        self.configurePusherForTest(self.props.user);
        self.getChangeOverNotificationData(self.props.user,self.props.hostUrls.VehicleTrackingUrl);
     }
        setInterval(() => {
            if(self.props.user)
                self.getChangeOverNotificationData(self.props.user,self.props.hostUrls.VehicleTrackingUrl);
            }, 300000);
    }

    componentWillReceiveProps(nextProps){
        if(!checkDeepEquals(nextProps.user, this.props.user)){
            if(nextProps.user){
                this.setState({user: nextProps.user});
                this.getChangeOverNotificationData(nextProps.user,nextProps.hostUrls.VehicleTrackingUrl);
                this.configurePusherForTest(nextProps.user);
            }
        }

        //console.log('inside bell component will recieve props with next props' , nextProps);
        if(!checkDeepEquals(nextProps.closeNotificationOnSave,this.props.closeNotificationOnSave)){
            //console.log('inside non equality check of props');
            if(nextProps.closeNotificationOnSave){
                //console.log('calling remove notification method');
                this.removeNotificationFromNotificationArray(nextProps.closeNotificationOnSave);
            }
        }else{
            //console.log('both next props are equal');
        }
    }

    removeNotificationFromNotificationArray(notification){
        let notificationsArray = this.state.notificationsArray;
        let pusherNotificationArray = this.state.pusherNotificationArray;
        //console.log('inside remove notification from notification array for ticket id ' , notification.ticketId);        
        let indexArray = [];
        let count = 0;
        let pusherIndexArray = [];
        let notificationCount = this.state.notificationCount;

        notificationsArray.forEach(function(ticket){
            if(ticket.entireData && ticket.entireData.ticketId){
                if(ticket.entireData.ticketId === notification.ticketId){
                    indexArray.push(count);
                }
            }
            count = count + 1;
        })

        if(indexArray.length > 0){
            indexArray.forEach(function(index){
            if(notificationsArray[index] && !notificationsArray[index].read){
                notificationCount = notificationCount - 1;
            }
                notificationsArray.splice(index,1);
            })          
        }

        count = 0;

           pusherNotificationArray.forEach(function(ticket){
            if(ticket.entireData && ticket.entireData.ticketId){
                if(ticket.entireData.ticketId === notification.ticketId)
                    pusherIndexArray.push(count);
            }
            count = count + 1;
        })

          if(pusherIndexArray.length > 0){
            pusherIndexArray.forEach(function(index){             
                pusherNotificationArray.splice(index,1);
            })          
        }   

        this.setState({
            notificationsArray : notificationsArray,
            notificationCount : notificationCount,
            pusherNotificationArray: pusherNotificationArray
        })

    }


   getChangeOverNotificationData(user,VehicleTrackingUrl){
        let domain = this.props.tripDomain;
         let url =  `${VehicleTrackingUrl}api/v1/actions/changeover`;
        if(domain){
            url = `${domain}/api/v1/actions/changeover`;
        }
        let params = {user: user};
        let promise = doHttpGet(url, params);
        promise.then((response) => {
            if (response.status === 200) {
                let notificationData  = response.data;

                let notificationsArray = this.state.pusherNotificationArray;

                let notificationDataCount = 0;
                notificationData.forEach((notification) => {
                    if(notification.aboutToVanish === true && notification.forTripClosureFilter) {
                        let notificationEntry = this.createNotificationEntryChangeover(notification);
                        notificationEntry.data = this.createRowEntryInRequiredFormatChangeover(notification);
                        notificationsArray = [notificationEntry, ...notificationsArray];
                        notificationDataCount++;
                    }

                    if(notification.nodeTrackingOverrideTypeMap && notification.nodeTrackingOverrideTypeMap['TDS_HOLD']){
                        notification.tdsDepartureTimestamp = notification.nodeTrackingOverrideTypeMap['TDS_HOLD'];

                        let notificationEntry = this.createNotificationEntryChangeoverForTds();
                        notificationEntry.data = this.createRowEntryInRequiredFormatChangeover(notification);
                        notificationsArray = [notificationEntry, ...notificationsArray];
                        notificationDataCount++;
                    }
                });


               let notificationCount = this.state.unreadPusherNotificationCount + notificationDataCount;
               let primeNotificationCount =  notificationDataCount;

               this.setState({
                notificationsArray : notificationsArray ,
                notificationCount : notificationCount,
                primeNotificationCount:  primeNotificationCount
               })

               }})     
            , (err) => {

        }
    }

   createNotificationEntryChangeover(data){
    let notificationEntry = {};
    notificationEntry.data = {};
    notificationEntry.alertType = "tripClosure";
    let title = "";
    if(data.forTripAdvanceFilter && !data.forTripClosureFilter)
        title = "Pending Trip Advance";
    else if(data.forTripClosureFilter && !data.forTripAdvanceFilter)
        title = "Pending Trip Closure";
    else if(data.forTripClosureFilter)
        title = "Pending Trip Closure";

    notificationEntry.title = title;
    notificationEntry.read = false;
    return notificationEntry;
}

    createNotificationEntryChangeoverForTds(){
        let notificationEntry = {
            data: {},
            alertType: "tds",
            title: "Pitstop Hold - TDS",
            read: false
            };

        return notificationEntry;
    }

createRowEntryInRequiredFormatChangeover(el){

    let rowEntery = {};
    rowEntery["tripCode"] = el["tripCode"]?el["tripCode"]:'--';

    let len = rowEntery['tripCode'].length;
    for(let i=0;i< len ;i++){
        if(rowEntery['tripCode'][i] === '|'){
            rowEntery['tripCode'] = rowEntery['tripCode'].substr(0,i) + ' | ' +
                rowEntery['tripCode'].substr(i+1,rowEntery['tripCode'].length -i-1);
            i++;
        }
    }
    rowEntery["vehicleNumber"] = el["vehicleNumber"]?el["vehicleNumber"]:'--';
    rowEntery["reason"] = el["reason"]?el["reason"]:'--';
    rowEntery["comment"] = el["comment"]?el["comment"]:'--';
    rowEntery["tdsDepartureTimestamp"] = dateFormatter(el["tdsDepartureTimestamp"]);
    rowEntery.vehicleNodeTrackingId = el.vehicleNodeTrackingId?el.vehicleNodeTrackingId:'-';

    return rowEntery;

}

  pusherDataUpdate(data){
        //console.log('Notification received', data);
        let notificationEntry=  headerActions.createNotificationEntry(data);
        
        let rowEntry = headerActions.createRowEntryInRequiredFormat(data.ticketMetadataInfoDto);
        notificationEntry.data = rowEntry;
        notificationEntry.entireData = headerActions.createRowEntryInRequiredFormatForEdit(data.ticketMetadataInfoDto);
        let notificationsArray = this.state.notificationsArray;
        let pusherNotificationArray = this.state.pusherNotificationArray;
        notificationsArray = [notificationEntry, ...notificationsArray];
        pusherNotificationArray = [notificationEntry, ...pusherNotificationArray];
        let notificationCount = this.state.notificationCount + 1;
        let unreadPusherNotificationCount = this.state.unreadPusherNotificationCount + 1;
        if(this.props.onPusherNotification){
            this.props.onPusherNotification(data.ticketMetadataInfoDto);
        }
        this.setState({
            notificationsArray : notificationsArray,
            notificationCount : notificationCount,
            pusherNotificationArray : pusherNotificationArray,
            unreadPusherNotificationCount: unreadPusherNotificationCount
        })

        //this.props.
    }

    
//call this from edit alert
    updateNotificationArrayOnEdit = (ticketId) => {
        let notificationsArray = this.state.notificationsArray;

        let index =  _.findIndex(notificationsArray, function(ticket) { return ticket.data.ticketId  === ticketId });
        if(index !== -1){
        notificationsArray.splice(index,1);
        }

        this.setState({
            notificationsArray : notificationsArray
        });
    }

    updateNotificationsOnClick(){
        //console.log('Bell state noti', this.state);
        let notificationsArray = this.state.notificationsArray;
        let showModal = this.state.showModal;
        let notificationCount = this.state.notificationCount;

        if(showModal){
        notificationsArray.forEach((notification) => {
          notification.read = true;
        });
        notificationCount = this.state.primeNotificationCount;
    }

    showModal = !showModal;

    this.setState({
        notificationsArray : notificationsArray,
        notificationCount : notificationCount,
        showModal : showModal,
        unreadPusherNotificationCount: 0
    })
    }

   

    configurePusherForTest(user){          
        let pusherKey = pusherConst.pusherKey;
        let pusherCluster = pusherConst.pusherCluster ;
        let pusherAppId = pusherConst.pusherAppId;
        let pusherSecret = pusherConst.pusherSecret;
        let pusherEnv = pusherConst.pusherEnv;

        let pusher = new Pusher(pusherKey, {
            cluster: pusherCluster
        });

        let email = user.email;
        /*let state = getState().toJS();
        let emailId = getState().toJS().userProfile.userProfile.email;*/

        var channel = pusher.subscribe(email);
        let channels = [];
        // pusherConst.subscribingChanels.forEach((chanel) => {
        //     channels.push(pusher.subscribe(chanel));
        // })

        let self = this;
        let handler = function (data) {
            self.pusherDataUpdate(data);
        }

        // channels.forEach((channel)=>{
        channel.bind('ticketing-service',handler);
        // });
    
}


    onClick(){
        this.updateNotificationsOnClick(this.state.showModal);
    }

    handleModalClose(){
        // this.setState({showModal: false});
        //console.log('Bell state', this.state);
        this.setState({showEditModal: false});
        this.updateNotificationsOnClick(this.state.showModal);
    }

    handleModalOpen(data){
        this.setState({ticketData: data, showEditModal: true});
    }


    render(){

        return(
            <div className="BellWrap ui-commons">
                <div className="bell-content" onClick={this.onClick.bind(this)}>
                        
                        { this.state.notificationCount ?                                
                            (<Badge
                                badgeContent={this.state.notificationCount}
                                primary={true}
                                badgeStyle= {{backgroundColor:'#dd712f', fontSize: '10px', width: '8px',
                                                height: '8px' ,top: '18px' ,right:'22px', padding: '5px'}}
                             >                  
                                <NotificationsIcon style={{ color:'#fafafa', cursor:'pointer'}}/>
                             </Badge> ) 
                             :
                             (<Badge
                                badgeContent={this.state.notificationCount}
                                primary={true}
                                badgeStyle= {{display:'none'}}
                             >                  
                                <NotificationsIcon style={{ color:'#fafafa',cursor:'pointer'}}/>
                             </Badge> 
                             ) 
                        }
                        {(this.state.showModal) && (<div className="up-arrow" />)}
                    </div>

                     {
                         (this.state.showModal) &&
                            (
                                <NotificationBar
                                    onModalOpen ={(data) => this.handleModalOpen(data)}
                                    onModalClose ={this.handleModalClose.bind(this)}
                                    hostUrls={this.props.hostUrls}
                                    onNotificationClick={this.props.onNotificationClick?this.props.onNotificationClick:null}
                                    {... this.state}
                                />
                            )
                     }
                    {
                        this.state.showEditModal?
                            <EditAlerts
                                showEditModal={this.state.showEditModal}
                                data={this.state.ticketData}
                                user={this.props.user}
                                isCalledFromAnotherRepo={true}
                                onModalClose={this.handleModalClose.bind(this)}
                                hostUrls={this.props.hostUrls}
                                closeNotificationOnSave={this.removeNotificationFromNotificationArray.bind(this)}
                                selectedTab={this.state.ticketData.ticketType}
                            />
                            :''

                    }
                     </div>
            )       
    }}
    
