import {camelCaseToNormalString} from '../../UtilitiesFunctions/objectUtilities';
import moment from "moment";


export function sortAndConvertCommentHistory(comments, documents) {
    let data = [];
    let historyLength = comments.length + documents.length;
    let j = 0, k = 0;
    for(let i=0; i< historyLength; i++){
        if(j >= comments.length)
            data.push(convertDocument(documents[k++]));
        else if(k >= documents.length)
            data.push(convertComment(comments[j++]));
        else{
            if(comments[j]["lastUpdatedTimestamp"] > documents[k]["lastUpdatedTimestamp"])
                data.push(convertDocument(documents[k++]));
            else
                data.push(convertComment(comments[j++]));
        }
    }
    return data;
}

export function convertComment(comment){
    let commentHistory = {};
    let initial = "--";
    if(comment.userDetail && comment.userDetail.name){
        let nameArr = comment.userDetail.name.split(' ');
        initial = nameArr[0].substr(0, 1) + (nameArr[1]?(nameArr[1].substr(0, 1)):'');
    }

    commentHistory['timestamp'] = comment.lastUpdatedTimestamp
    commentHistory['message'] = comment.commentText;
    commentHistory['name'] = initial.toUpperCase();
    commentHistory['title'] = (comment.userDetail && comment.userDetail.name)?comment.userDetail.name:'';
    commentHistory['type'] = 'Comment';
    commentHistory['contactNumber'] = (comment.userDetail && comment.userDetail.contactNumber)?comment.userDetail.contactNumber:'';
    commentHistory['department'] = (comment.userDetail && comment.userDetail.department)?comment.userDetail.department:''
    return commentHistory;
}
export function convertDocument(document){
    let commentHistory = {};
    let initial = "--";
    if(document.userDetail && document.userDetail.name){
        let nameArr = document.userDetail.name.split(' ');
        initial = nameArr[0].substr(0, 1) + (nameArr[1]?(nameArr[1].substr(0, 1)):'');
    }
    commentHistory['timestamp'] = document.lastUpdatedTimestamp
    commentHistory['documentName'] = document.documentName;
    commentHistory['url'] = document.url;
    commentHistory['name'] = initial.toUpperCase();
    commentHistory['title'] = (document.userDetail)?document.userDetail.name:'';
    commentHistory['type'] = 'Document';
    commentHistory['contactNumber'] = (document.userDetail && document.userDetail.contactNumber)?document.userDetail.contactNumber:'';
    commentHistory['department'] = (document.userDetail && document.userDetail.department)?document.userDetail.department:'';
    return commentHistory;
}

export function convertFilterValues(data, asigneeDetails, EditModalDropDownData, filterValues) {
    let keys = Object.keys(data);
    /*for(let i=0; i<keys.length; i++){
        let item = data[keys[i]];
        if(keys[i] === "INFORM"){
            filterValues["Inform To"] = [];
            item.forEach((informItem) => {
               filterValues["Inform To"].push({value: informItem.userId, label: informItem.name});
            });
        }
        else if(keys[i] === "ESCALATE"){
            filterValues["Escalate To"] = [];
            item.forEach((informItem) => {
                filterValues["Escalate To"].push({value: informItem.userId, label: informItem.name});
            });
        }
    }*/

    if(asigneeDetails && asigneeDetails.userId){
        // let index = _.findIndex(EditModalDropDownData, function(data) { return data.label  === "Assign To" });
        // let indexData =  _.findIndex(EditModalDropDownData[index].data, function(item) { return item.value  === asigneeDetails.userId});
        let dropdownDataValue = {value: asigneeDetails.userId, label: asigneeDetails.name};

        filterValues["Assign To"] = dropdownDataValue;
    }

    return filterValues;
}


export function populateEditModalDropdownValues(filterValues, EditModalDropDownData){
    EditModalDropDownData.forEach((data, i) => {
        if(filterValues && filterValues[data.label]){
            EditModalDropDownData[i]["value"] = filterValues[data.label];
        }
        else if(data.label === "Inform To" || data.label === "Escalate To"){
            EditModalDropDownData[i]["value"] = [];
        }
        else{
            EditModalDropDownData[i]["value"] = {};
        }
    });
    let index = _.findIndex(EditModalDropDownData, function(data) { return data.label  === "Assign To" });
    if(index >= 0)
        EditModalDropDownData[index]["value"] = filterValues["Assign To"];
    console.log('EditModalDropDownData', EditModalDropDownData, filterValues);
    return EditModalDropDownData;
}
export function populateFilterValues(data,editModalDropDownData){
    let filterValues = [];

    editModalDropDownData.forEach((entry, i) => {
        if(entry && entry.value && (((Array.isArray(entry.value)) && entry.value.length > 0) 
            || (!((Array.isArray(entry.value)) && entry.value.hasOwnProperty('value'))))){
            filterValues[entry.label] = entry.value;
        }
        
    });

    if(data['expectedUnloadingTimestamp']){
        filterValues['Expected Unloading Time'] = {label:'expectedUnloadingTimestamp',value:parseInt(data['expectedUnloadingTimestamp'])}; 
    }

     if(data['actualUnloadingTimestamp']){
        filterValues['Actual Unloading Time'] = {label:'actualUnloadingTimestamp', value:parseInt(data['actualUnloadingTimestamp'])}; 
    }

    if(data['eta']){
        filterValues['ETA'] = {label:'eta',value:parseInt(data['eta'])}; 
    }

    if(data['cwhReachedTimestamp']){
        filterValues["Cwh Reached At"] = {label:'cwhReachedTimestamp',value:parseInt(data['cwhReachedTimestamp'])}; 
    }
    /*if(reason && reason !== '')
        filterValues["Select Reason"] = {label: reason, value: reason};
    if(assigned && assigned !== '')
        filterValues["Assign To"] = assigned;*/
    return filterValues;
}

export function modifyFilterValues(filter){

    let filterValues = Object.assign({},filter);

    if(!filterValues['Expected Unloading Time'] || !(filterValues['Expected Unloading Time'].value)){
        filterValues['Expected Unloading Time'] = {label:'expectedUnloadingTimestamp',value:new moment().valueOf()};
    }


    if(!filterValues['Actual Unloading Time'] || !(filterValues['Actual Unloading Time'].value)){
        filterValues['Actual Unloading Time'] = {label:'actualUnloadingTimestamp',value:new moment().valueOf()};
    }


    if(!filterValues['ETA'] || !(filterValues['ETA'].value)){
        filterValues['ETA'] = {label:'eta',value:new moment().valueOf()};
    }


    if(!filterValues['Cwh Reached At'] || !(filterValues['Cwh Reached At'].value)){
        filterValues['Cwh Reached At'] = {label:'cwhReachedTimestamp',value:new moment().valueOf()};
    }

    return filterValues;
}


export function getInputData(data, label, multiLabel,multiSelect, filterValues,type,showFlag,key) {
    let inputValues = {};
    inputValues.label = label;
    inputValues.data = data;
    inputValues.multiLable = multiLabel;
    inputValues.multiSelect=multiSelect;
    inputValues.value=filterValues[label]?filterValues[label]:{};
    inputValues.type = type;
    inputValues.show = showFlag;
    inputValues.key = key;
    return inputValues;
}

export function getEditModalDropdownData(){
    let dropdownData =  [{
        label: 'Select Reason',
        data: [],
        multiLable: false,
        multiSelect: false,
        value: {}
    },{
        label: 'Assign To',
        data: [],
        multiLable: false,
        multiSelect: false,
        value: {}
    },{
        label: 'Inform To',
        data: [],
        multiLable: false,
        multiSelect: true,
        value: []
    },{
        label: 'Escalate To',
        data: [],
        multiLable: false,
        multiSelect: true,
        value: []
    }];
    return dropdownData;
}

export function getBreakdownReasons(){
    let dropdownData =  {
        label: 'Select SubReason',
        data: [{
            label: 'Headlight/Indicator/Horn',
            value: 'Headlight/Indicator/Horn'
        },{
            label: 'Wiper',
            value: 'Wiper'
        },{
            label: 'Starting',
            value: 'Starting'
        },{
            label: 'Accelerator',
            value: 'Accelerator'
        },{
            label: 'Side Mirror/Glass Repair',
            value: 'Side Mirror/Glass Repair'
        },{
            label: 'Brakes',
            value: 'Brakes'
        },{
            label: 'Suspension/Chassis/Body',
            value: 'Suspension/Chassis/Body'
        },{
            label: 'Gear',
            value: 'Gear'
        },{
            label: 'Engine (Over-Heating/Oil/Others)',
            value: 'Engine (Over-Heating/Oil/Others)'
        },{
            label: 'Others',
            value: 'Others'
        }],
        multiLable: false,
        multiSelect: false,
        value: {}
    };
    return dropdownData;
}

export function getEditColumns(){
    let columns = {
      'TOUCHING_MISSING': [{Header: 'Trip Code', id: 'tripCode'},
                          {Header: 'Vehicle Details', id: 'vehicleNoType'},
                          {Header: 'Pilot Details', id: 'pilotDetails'},
                          {Header: 'Missing CWH', id: 'missingCwh'}
                            ],
        'PS_WAITING': [{Header: 'Trip Code', id: 'tripCode'},
            {Header: 'Vehicle Details', id: 'vehicleNoType'},
            {Header: 'Pilot Details', id: 'pilotDetails'},
            {Header: 'Pitstop', id: 'pitstopCode'}
        ],
        'ROUTE_DETOUR': [{Header: 'Trip Code', id: 'tripCode'},
            {Header: 'Vehicle Details', id: 'vehicleNoType'},
            {Header: 'Pilot Details', id: 'pilotDetails'},
            {Header: 'Previous Hub', id: 'pitstopCode'}
        ],
        'UNSCHEDULED_STOPPAGE': [{Header: 'Trip Code', id: 'tripCode'},
            {Header: 'Vehicle Details', id: 'vehicleNoType'},
            {Header: 'Pilot Details', id: 'pilotDetails'},
            {Header: 'Last Known Location', id: 'currentLocation'}
        ]
    };
    return columns;
}