/**
 * Created by Benny on 12.10.2014.
 */
"use strict";

var TB = TB || {};

TB.Utils = {
    ucfirst : function( str ) {
        return str.charAt(0).toUpperCase() + str.slice(1);
    },
    getUnixTimestampFromDatetimeString : function( stringValue ) {
        if ( stringValue ) {
            return ~~(Date.parse( Date.parseDate( stringValue, 'DD.MM.YYYY H:mm'  ) ) / 1000);
        } else {
            return 0;
        }
    },
    getUnixTimestampFromDateString : function( stringValue ) {
        if ( stringValue ) {
            return ~~(Date.parse( Date.parseDate( stringValue, 'DD.MM.YYYY'  ) ) / 1000);
        } else {
            return 0;
        }
    },
    getDateStringFromUnixTimestamp : function( timestamp ) {
        return moment( new Date( timestamp * 1000 ) ).format( 'DD.MM.YYYY' );
    },

    getDatetimeStringFromUnixTimestamp : function( timestamp ) {
        return moment( new Date( timestamp * 1000 ) ).format( 'DD.MM.YYYY H:mm' );
    },

    getDatetimeStringFromTimeString : function( timeString ) {
        return moment( new Date( timeString ) ).format( 'DD.MM.YYYY [um] H:mm [Uhr]' );
    },

    getDatetimeStringFromUnixTimestampShortYear : function( timestamp ) {
        return moment( new Date( timestamp * 1000 ) ).format( 'DD.MM.YY H:mm' );
    },

    getDatetimeStringFromUnixTimestampMini : function( timestamp ) {
        return moment(new Date(timestamp * 1000)).format('DD.MM.');
    },

    getTimeStringFromUnixTimestampMini : function( timestamp ) {
        return moment(new Date(timestamp * 1000)).format('HH:mm' );
    },

    getDateFromUnixTimestamp : function( timestamp ) {
        return new Date( timestamp * 1000 );
    },

    getUnixTimestamp : function() {
        return ~~ ( new Date().getTime() / 1000 );
    },

    convertSQLDateToDatepickerDate : function( mysqlDate ) {
        return moment( mysqlDate).format( 'DD.MM.YYYY' );
    },

    convertDatepickerDateStringToSQLDate : function( timepickerDate ) {
        return moment( new Date( TB.Utils.getUnixTimestampFromDateString( timepickerDate ) * 1000 ) ).format( 'YYYY-MM-DD' );
    },

    isValidDate : function( d ) {
        if ( Object.prototype.toString.call(d) !== "[object Date]" )
            return false;
        return !isNaN(d.getTime());
    },
    inIframe : function() {
        try {
            return window.self !== window.top;
        } catch (e) {
            return true;
        }
    },
    getPercentFromFloat : function( fl ) {
        //return (fl*100).toFixed(1);
        return ~~( fl * 100 );
    },
    trackEvent : function( category, action, label, value ) {
        try {
            ga('send', 'event', category, action, label, value);
        } catch ( e ) {
            // Fail silently
        }
    },
    getWhatsAppUrl : function( text, redirectHash )
    {
        var wa = 'whatsapp://send?text=';

        wa += encodeURI( text + " - " );
        wa += encodeURIComponent( TB.Client.clientUrl + '/#/c=Auth&a=redirect&redirect=' + redirectHash );

        return wa;
    }
    ,
    getRedirectUrl : function( c, a, params, targetTeamId )
    {
        var redirectHash, url;

        redirectHash = TB.Utils.encodeRedirect( c, a, params, targetTeamId );
        url = TB.Client.clientUrl + '/' + TB.Controller.getUrl( 'Auth', 'redirect', { redirect : redirectHash } );

        return url;
    }
    ,
    encodeRedirect : function( c, a, params, targetTeamId )
    {
        var reObj = {};

        reObj.c = c || 'News';
        reObj.a = a || 'index';
        reObj.targetTeamId = targetTeamId || null;
        reObj.params = params || {};

        return btoa( JSON.stringify( reObj ) );
    },
    decoreRedirect : function( encoded )
    {
        var reObj = null,
            json;
        try
        {
            json = atob( encoded );
            reObj = JSON.parse( json );
        }
        catch ( e )
        {
            reObj = null;
        }

        return reObj;
    },
    getAppointmentName : function( appointment )
    {
        if ( appointment.subject )
        {
            return appointment.subject;
        }
        else
        {
            return appointment.home + " : " + appointment.guest;
        }
    },
    exportToCsv : function ( filename, rows, sep )
    {
        var seperator = sep || ',';

        var processRow = function (row)
        {
            var finalVal = '';
            for (var j = 0; j < row.length; j++) {
                var innerValue = row[j] === null ? '' : row[j].toString();
                if (row[j] instanceof Date)
                {
                    innerValue = row[j].toLocaleString();
                };
                var result = innerValue.replace(/"/g, '""');
                if ( result.search(/("|,|\n)/g) >= 0 )
                    result = '"' + result + '"';
                if (j > 0)
                    finalVal += seperator;
                finalVal += result;
            }
            return finalVal + '\n';
        };

        var csvFile = '';
        for (var i = 0; i < rows.length; i++)
        {
            csvFile += processRow(rows[i]);
        }

        var blob = new Blob([csvFile], { type: 'text/csv;charset=utf-8;' });
        if (navigator.msSaveBlob) { // IE 10+
            navigator.msSaveBlob(blob, filename);
        } else {
            var link = document.createElement("a");
            if (link.download !== undefined) { // feature detection
                // Browsers that support HTML5 download attribute
                var url = URL.createObjectURL(blob);
                link.setAttribute("href", url);
                link.setAttribute("download", filename);
                link.style.visibility = 'hidden';
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
            }
        }
    }
};

// https://github.com/carlsednaoui/add-to-calendar-buttons/blob/master/ouical.js
;(function(exports) {
    var MS_IN_MINUTES = 60 * 1000;

    var formatTime = function(date) {
        return date.toISOString().replace(/-|:|\.\d+/g, '');
    };

    var calculateEndTime = function(event) {
        return event.end ?
            formatTime(event.end) :
            formatTime(new Date(event.start.getTime() + (event.duration * MS_IN_MINUTES)));
    };

    var calendarGenerators = {
        google: function(event) {
            var startTime = formatTime(event.start);
            var endTime = calculateEndTime(event);

            var href = encodeURI([
                'https://www.google.com/calendar/render',
                '?action=TEMPLATE',
                '&text=' + (event.title || ''),
                '&dates=' + (startTime || ''),
                '/' + (endTime || ''),
                '&details=' + (event.description || ''),
                '&location=' + (event.address || ''),
                '&sprop=&sprop=name:'
            ].join(''));
            return '<a class="icon-google" target="_blank" href="' +
            href + '">Google Kalender</a>';
        },

        yahoo: function(event) {
            var eventDuration = event.end ?
                ((event.end.getTime() - event.start.getTime())/ MS_IN_MINUTES) :
                event.duration;

            // Yahoo dates are crazy, we need to convert the duration from minutes to hh:mm
            var yahooHourDuration = eventDuration < 600 ?
            '0' + Math.floor((eventDuration / 60)) :
            Math.floor((eventDuration / 60)) + '';

            var yahooMinuteDuration = eventDuration % 60 < 10 ?
            '0' + eventDuration % 60 :
            eventDuration % 60 + '';

            var yahooEventDuration = yahooHourDuration + yahooMinuteDuration;

            // Remove timezone from event time
            var st = formatTime(new Date(event.start - (event.start.getTimezoneOffset() *
                MS_IN_MINUTES))) || '';

            var href = encodeURI([
                'http://calendar.yahoo.com/?v=60&view=d&type=20',
                '&title=' + (event.title || ''),
                '&st=' + st,
                '&dur=' + (yahooEventDuration || ''),
                '&desc=' + (event.description || ''),
                '&in_loc=' + (event.address || '')
            ].join(''));

            return '<a class="icon-yahoo" target="_blank" href="' +
            href + '">Yahoo! Kalender</a>';
        },

        ics: function(event, eClass, calendarName) {
            var startTime = formatTime(event.start);
            var endTime = calculateEndTime(event);

            var href = encodeURI(
                'data:text/calendar;charset=utf8,' + [
                    'BEGIN:VCALENDAR',
                    'VERSION:2.0',
                    'BEGIN:VEVENT',
                    'URL:' + document.URL,
                    'DTSTART:' + (startTime || ''),
                    'DTEND:' + (endTime || ''),
                    'SUMMARY:' + (event.title || ''),
                    'DESCRIPTION:' + (event.description || ''),
                    'LOCATION:' + (event.address || ''),
                    'END:VEVENT',
                    'END:VCALENDAR'].join('\n'));

            return '<a class="' + eClass + '" target="_blank" href="' +
            href + '" download="teamtermin.ics">' + calendarName + ' Kalender</a>';
        },

        ical: function(event) {
            return this.ics(event, 'icon-ical', 'iCal');
        },

        outlook: function(event) {
            return this.ics(event, 'icon-outlook', 'Outlook');
        }
    };

    var generateCalendars = function(event) {
        return {
            google: calendarGenerators.google(event),
            yahoo: calendarGenerators.yahoo(event),
            ical: calendarGenerators.ical(event),
            outlook: calendarGenerators.outlook(event)
        };
    };

    // Create CSS
    var addCSS = function() {
        if (!document.getElementById('ouical-css')) {
            document.getElementsByTagName('head')[0].appendChild(generateCSS());
        }
    };

    var generateCSS = function() {
        var styles = document.createElement('style');
        styles.id = 'ouical-css';

        styles.innerHTML = "#add-to-calendar-checkbox-label{cursor:pointer}.add-to-calendar-checkbox~a{display:none}.add-to-calendar-checkbox:checked~a{display:block;width:150px;margin-left:20px}input[type=checkbox].add-to-calendar-checkbox{position:absolute;top:-9999px;left:-9999px}.add-to-calendar-checkbox~a:before{width:16px;height:16px;display:inline-block;background-image:url(data:image/png;base64, );margin-right:.5em;content:' '}.icon-ical:before{background-position:-68px 0}.icon-outlook:before{}.icon-yahoo:before{background-position:-36px +4px}.icon-google:before{background-position:-52px 0}";

        return styles;
    };

    // Make sure we have the necessary event data, such as start time and event duration
    var validParams = function(params) {
        return params.data !== undefined && params.data.start !== undefined &&
        (params.data.end !== undefined || params.data.duration !== undefined);
    };

    var generateMarkup = function(calendars, clazz, calendarId) {
        var result = document.createElement('div');

        result.innerHTML = '<label for="checkbox-for-' +
        calendarId + '" class="add-to-calendar-checkbox">+ Add to my Calendar</label>';
        result.innerHTML += '<input name="add-to-calendar-checkbox" class="add-to-calendar-checkbox" id="checkbox-for-' + calendarId + '" type="checkbox">';

        Object.keys(calendars).forEach(function(services) {
            result.innerHTML += calendars[services];
        });

        result.className = 'add-to-calendar';
        if (clazz !== undefined) {
            result.className += (' ' + clazz);
        }

        addCSS();

        result.id = calendarId;
        return result;
    };

    var getClass = function(params) {
        if (params.options && params.options.class) {
            return params.options.class;
        }
    };

    var getOrGenerateCalendarId = function(params) {
        return params.options && params.options.id ?
            params.options.id :
            Math.floor(Math.random() * 1000000); // Generate a 6-digit random ID
    };

    exports.createCalendar = function(data) {
        return generateCalendars(data);
        /*
        return generateMarkup(generateCalendars(params.data),
            getClass(params),
            getOrGenerateCalendarId(params));

            */
    };
})(TB.Utils);