import _ from 'lodash';
import moment from 'moment';
import ReactGA from 'react-ga';

export function checkDeepEquals(obj1, obj2) {
    return _.isEqual(obj1, obj2);
}
export function cloneDeep(obj1) {
    return _.cloneDeep(obj1)
}
export function dateFormatter(date, format='DD-MM-YYYY | HH:mm') {
    //DD-MM-YYYY|HH:mm
    //MMM D, YYYY HH:mm
    return date ? moment(Number(date)).format(format) : '';
}

export function timeDifferenceInDaysAndHours(t1, t2){
    if(!t2 && !t1){
        return;
    }

    var fTime = Math.floor((t2 - t1)/1000);
    var timeString = null;
    if(fTime < 60){
        return 'few seconds ';
    } else {
        let mins = Math.floor(fTime / 60);
        let hrs = 0;
        let days =0;
        if(mins < 60){
            return mins + (mins === 1 ? ' min ':' mins ');
        }

         hrs = Math.floor(mins / 60);            
         mins = mins - hrs*60;
        
        if(hrs > 24){
            days = Math.floor(hrs / 24);
            hrs = hrs - 24*days;                
            }

            if(days > 0){
            timeString = days + (days === 1 ? ' day' : ' days');                
            }

            if(hrs > 0){
                timeString = (timeString ? timeString + ' ' : '' ) 
                + hrs + (hrs === 1 ? ' hr' : ' hrs');
            }

            if(mins > 0){
                 timeString = (timeString ? timeString + ' ' : '' )
                  + mins + (mins === 1 ? ' min' : ' mins');
            }

            return timeString;
        
    }
}

export function triggerGAEvent(category, action, label='', value=0){
    ReactGA.event({
        category: category,
        action: action,
        label: label,
        value: value
    });
}

export function debounce(func, wait=200, immediate=false) {
    let timeout;
    return function() {
        let context = this, args = arguments;
        let later = function() {
            timeout = null;
            if (!immediate) func.apply(context, args);
        };
        let callNow = immediate && !timeout;
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
        if (callNow) func.apply(context, args);
    };
}

export function throttle(fn, threshhold, scope) {
  threshhold || (threshhold = 250);
  var last,deferTimer;
  return function () {
    var context = scope || this;

    var now = +new Date,
        args = arguments;
    if (last && now < last + threshhold) {
      // hold on to it
      clearTimeout(deferTimer);
      deferTimer = setTimeout(function () {
        last = now;
        fn.apply(context, args);
      }, threshhold);
    } else {
      last = now;
      fn.apply(context, args);
    }
  };
}

export function JSONToCSVConvertor(JSONData, fileTitle='MyFile', extension='.csv') {
    var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData;
    var CSV = '';
    var row = '',
        headers = [];
    for (var index in arrData[0]) {
        row += index + ',';
        headers.push(index);
    }

    row = row.slice(0, -1);

    CSV += row + '\r\n';
    for (var i = 0; i < arrData.length; i++) {
        row = '';

        for (var k = 0; k < headers.length; k++) {
            row += '"' + arrData[i][headers[k]] + '",';
        }

        row.slice(0, row.length - 1);

        CSV += row + '\r\n';
    }

    if (CSV === '') {
        alert('Invalid data');
        return;
    }

    var fileName = '';
    fileName += fileTitle.replace(/ /g, '_');
    var uri = 'data:text/xls;charset=utf-8,' + escape(CSV);

    var link = document.createElement('a');
    link.href = uri;
    link.style.visibility = 'hidden';
    link.download = fileName + extension;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}

export function scrollTo(element, nextPosition, direction='vertical',scrollDuration=300){
  let currentPosition = direction=='vertical' ? element.scrollTop : element.scrollLeft,
      scrollCount = 0,
      scrollMargin,
      totalScrollSteps = scrollDuration/15,
      scrollStep = (nextPosition-currentPosition)/totalScrollSteps,
      scrollInterval = setInterval(function() {
          if(scrollCount<=totalScrollSteps) {
              scrollCount++;
              scrollMargin = currentPosition + scrollStep*scrollCount;
              direction=='vertical' ? element.scrollTop=scrollMargin : element.scrollLeft=scrollMargin
          }
          else clearInterval(scrollInterval);
      }, 15);
}