/*
    Copyright 2015 Adobe Systems Incorporated.  All rights reserved. 
*/
/*global $, console*/
/*jslint regexp: true, vars:true*/

function DevicePreviewUtils() {
    'use strict';
    this.getIndicesOf = function (searchStr, str, caseSensitive) {
        var startIndex = 0, searchStrLen = searchStr.length, index, indices = [];
        if (!caseSensitive) {
            str = str.toLowerCase();
            searchStr = searchStr.toLowerCase();
        }
        while ((index = str.indexOf(searchStr, startIndex)) > -1) {
            indices.push(index);
            startIndex = index + searchStrLen;
        }
        return indices;
    };
    
    this.sprintf = function () {
        // Basic implementation of sprintf to work for only %s. Will not handle any other format specifier - not even %%.
        var formatString = arguments[0],
            formattersLocation = this.getIndicesOf("%s", formatString, false),
            formatLength = formattersLocation.length;
        if (formatLength !== arguments.length - 1) {
            throw new SyntaxError("[sprintf] format specifers does not match with parameters passed ");
        }
        while (formatLength > 0) {
            formatString = formatString.replace("%s", arguments[formattersLocation.length - formatLength + 1].toString());
            formatLength = formatLength - 1;
        }
        return formatString;
    };
    
    this.XReqIdRoot = 'DwDevicePreview-';
    
    this.generateUUID = function () {
		var d = new Date().getTime();
		return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
			var r = (d + Math.random() * 16) % 16 | 0;
			d = Math.floor(d / 16);
			return (c === 'x' ? r : (r & 0x7 | 0x8)).toString(16);
		});
    };
    
    this.generateDevicePreviewClientRequestId = function () {
		return this.XReqIdRoot + this.generateUUID();
    };
    
    this.createAjaxOptions = function (type, location) {
        var options = {
            'type': type,
            'url': window.preview.environment.PREVIEW_SERVICE.HOST + location + '?api_key=Preview1',
            contentType: "application/json",
            'headers': {
                'Authorization': 'Bearer ' + window.preview.main.getAccessToken(),
                'x-request-id': this.generateDevicePreviewClientRequestId()
            }
        };
        return options;
    };
    
    this.doAjaxRequest = function (location, method, data, successCallback, errorCallback) {
        var ajaxOptions = this.createAjaxOptions(method, location);
        var requestID = ajaxOptions.headers['x-request-id'];
        if (data) {
            ajaxOptions.data = data;
        }
        $.ajax(ajaxOptions).fail(function (jqXHR, textStatus, errorThrown) {
            // We got an error trying to run the work not sure what to do here
            var debugParams = {};
            debugParams.eventname = "DevicePreviewFailedReqID";
            debugParams.subevent = requestID;
            window.preview.metricsController.trackDebugEvent(debugParams);
            errorCallback.call(jqXHR, errorThrown);
        }).done(function (data, textStatus, jqXHR) {
            successCallback.call(jqXHR, data);
        });
    };
    
    this.getShortUrl = function (longUrl, login, apiKey, callback) {
        $.getJSON(
            "http://api.bitly.com/v3/shorten?callback=?",
            {
                "format": "json",
                "apiKey": apiKey,
                "login": login,
                "longUrl": longUrl
            },
            function (response) {
                callback(response.data.url);
            }
        );
    };
    
    this.getDevicesCount = function () {
        var count =  $('.devicesConnected > tbody').children().length;
        return count.toString();
    };
    
    this.translate = function (key) {
        return $.i18n.prop(key);
    };
    
    this.getTroubleshootingPageURL = function () {
        
        var locale = window.preview.main.getLocale();
        if (!locale) {
            locale = 'en'; //Default to English   
        }
        
        return 'https://www.adobe.com/go/dpts_' + locale;
    };
}

window.preview.utils = window.preview.utils || new DevicePreviewUtils();
window.getDevicesCount = window.preview.utils.getDevicesCount; //for the convenience of calling it from C++