
window.ajax_calls = [];
window.issue_data = {};

$.real_action = $.action;

$.action = function(data,success,error,progress) {
	if (!Date.now)  Date.now = function() { return new Date().getTime(); }
	ajax_calls.push({request : data,time:Date.now() });
	if(ajax_calls.length >10) ajax_calls.shift();
	$.real_action(data,success,error,progress);
}

//CHARGEMENT DE LA PAGE
function init_plugin_issue(){
	window.documentLoaded = false;
	switch($.urlParam('page')){

		case 'sheet.report':
			if($('.issue').hasClass('readonly')){
				$('#assign,#reportState,#tags').attr('readonly','readonly');
				init_components();
			}
			issue_issue_event_search();
		break;
		case 'list.issue':
			$('#issuereports').sortable_table({
				onSort : issue_issuereport_search
			});
		break
	}
	window.documentLoaded = true;
}

function issue_add(){
	var button = $('.issue-declare-button');
	if(button.attr('data-disabled')=='1') return;

	button.attr('data-disabled',1);
	button.find('i.fa-bug').addClass('hidden');
	button.find('i.fa-cog').removeClass('hidden');

	issue_data.height = window.screen.availHeight;
	issue_data.width = window.screen.availWidth;
	issue_data.browser = '';

	//on utilise pas navigator.appName qui est un fake la plupart du temps
	issue_data.browser = issue_detect_browser();

	issue_data.browserVersion = navigator.appVersion;
	issue_data.online = navigator.onLine;
	issue_data.os = navigator.platform;
	issue_data.from = document.location.href;
	issue_data.history = JSON.stringify(ajax_calls);

	var modal = $('#issue-report-modal');
	reset_inputs(modal);
	$('.issue-screenshot').addClass('hidden').children().remove();
	$('span.badge.badge-tag.active', modal).removeAttr('style').removeClass('active');
	init_components('#issue-report-modal');
	modal.modal({
	    backdrop: 'static',
	    show: true
	});


	modal.on('shown.bs.modal', function () {
	    init_components(modal);
	});

	modal.on('hidden.bs.modal', function () {
	    button.removeAttr('data-disabled');
	});

	for(var key in issue_data){
		var element = $('[data-uid="'+key+'"]', modal);
		if(element.length == 0) continue;
		element.html(issue_data[key] == true ? 'OUI': issue_data[key]);
	}

	button.find('i.fa-cog').addClass('hidden');
	button.find('i.fa-bug').removeClass('hidden');
}

function issue_screenshot(){
	//Check if IE
    if (window.navigator.userAgent.indexOf("MSIE ") > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)){
    	alert('Unsupported html2canvas librairy (using ES6 features)');
    	console.warn('Unsupported html2canvas librairy (using ES6 features)');
    	return;
    }

	$('#issue-report-modal').modal('hide');
	setTimeout(function(){
		html2canvas(document.querySelector("html")).then(function(canvas){
		 	$('#issue-report-modal').modal('show');
		    issue_data.screenshot = canvas.toDataURL('image/jpg');
		    $('.issue-screenshot').removeClass('hidden').html('<img class="pointer" src="'+issue_data.screenshot+'"/>');
		     $('.issue-screenshot img').click(function(){
		     	var image = new Image();
		        image.src = issue_data.screenshot;
		        var popup = window.open("");
		        popup.document.write(image.outerHTML);
		     });
		});
	},500);
}

function issue_send(element){
	var sendButton = $(element);
	var closeButton = sendButton.closest('.modal-footer').find('.close-button');
	var modal = $('#issue-report-modal');
	var button = $('.issue-declare-button');

	sendButton.attr('disabled', true);
	closeButton.attr('disabled', true);
	sendButton.html('<i class="fas fa-spinner fa-pulse"></i> En cours d\'envoi...');

	issue_data.action = 'issue_issuereport_save';
	issue_data.tags = $('.issue-modal-tags').val();
	data = $.extend(issue_data,$('#issue-report-modal').toJson());

	$.action(data,function(response){
		issue_data = {};
		reset_inputs('#issue-report-modal');
		init_components('#issue-report-modal');

		sendButton.html('<i class="far fa-paper-plane"></i> Envoyer');
		sendButton.attr('disabled', false);
		closeButton.attr('disabled', false);

		modal.modal('hide');
		$.message('info','Rapport envoyé<br><a class="btn btn-mini text-light" href="index.php?module=issue&page=sheet.report&id='+response.item.id+'">> Consulter le rapport</a>',10000);
	},function(error){
		button.removeAttr('data-disabled');
		sendButton.html('<i class="far fa-paper-plane"></i> Envoyer');
		sendButton.attr('disabled', false);
		closeButton.attr('disabled', false);
		sendButton.removeClass('hidden');
		issue_issuereport_search();
	});
}

function issue_detect_browser(){
	// Opera 8.0+
	var isOpera = (!!window.opr && !!opr.addons) || !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
	// Firefox 1.0+
	var isFirefox = typeof InstallTrigger !== 'undefined';
	// Safari 3.0+ "[object HTMLElementConstructor]"
	var isSafari = /constructor/i.test(window.HTMLElement) || (function (p) { return p.toString() === "[object SafariRemoteNotification]"; })(!window['safari'] || (typeof safari !== 'undefined' && safari.pushNotification));
	// Internet Explorer 6-11
	var isIE = /*@cc_on!@*/false || !!document.documentMode;
	// Edge 20+
	var isEdge = !isIE && !!window.StyleMedia;
	// Chrome 1 - 68
	var isChrome = Boolean(window.chrome);
	// Blink engine detection
	var isBlink = (isChrome || isOpera) && !!window.CSS;

	if(isOpera) return 'opera';
	if(isFirefox) return 'firefox';
	if(isChrome) return 'chrome';
	if(isSafari) return 'safari';
	if(isIE) return 'ie';
	if(isEdge) return 'edge';
	if(isBlink) return 'blink';
	return 'inconnu';
}

function issue_follow_toggle(element){
	$.action({
		action : 'issue_follow_toggle',
		id : $('#issuereport-form').attr('data-id'),
		state : $(element).hasClass('followed') ? 0 : 1
	},function(){
		//@TODO: Améliorer la mise à jour de la liste des followers (passer via du moustache ?)
		$('.issue-followers').load(document.URL + ' .issue-followers>*');
		$(element).toggleClass('followed');
	});
}

//Enregistrement des configurations
function issue_setting_save(){
	$.action({
		action : 'issue_setting_save',
		fields : $('#issue-setting-form').toJson()
	},function(){
		$.message('success','Enregistré');
	});
}

/** ISSUEREPORT **/
//Récuperation d'une liste de issuereport dans le tableau #issuereports
function issue_issuereport_search(callback){
	var box = new FilterBox('#filters');

	$('#issuereports').fill({
		action:'issue_issuereport_search',
		filters : box.filters(),
		//differential: true,
		sort : $('#issuereports').sortable_table('get'),
		tags : $('#report-tags').val()
	},function(response){

		if(callback!=null) callback();
	});
}
//changement d'une meta de ticket (état, assiignation, tags...)
var tagsVal = $('#tags').val();
function issue_issuereport_meta_save(){
	if(!window.documentLoaded) return;

	$.action({
		action : 'issue_issuereport_meta_save',
		id : $('#issuereport-form').attr('data-id'),
		assign : $('#assign').val(),
		tags : $('#tags').val(),
		state : $('#reportState').val()
	},function(r){
		tagsVal = $('#tags').val();
		issue_issue_event_search();
	},function(r){
		$.each(tagsVal.split(','),function(i, val){
			var badge = $('.data-type-tagcloud span[data-slug="'+val+'"]');
			badge.addClass('active').css({
				background: badge.attr('data-color'),
				border: '1px solid '+badge.attr('data-color'),
				color: '#fff'
			});
		});
	});
}

//Suppression d'élement issuereport
function issue_issuereport_delete(element){
	if(!confirm('Êtes-vous sûr de vouloir supprimer ce ticket ?')) return;
	var line = $(element).closest('li');
	$.action({
		action : 'issue_issuereport_delete',
		id : line.attr('data-id')
	},function(r){
		line.remove();
		$.message('info','Ticket supprimé');
	});
}



/** ISSUEEVENT **/
//Récuperation d'une liste de issueevent dans le tableau #issueevents
function issue_issue_event_search(callback){
	if(isProcessing) return;

	isProcessing = true;
	$('.issue-events').fill({
		//differential :  true,
		action:'issue_issue_event_search',
		issue : $('#issuereport-form').attr('data-id'),
		templating : function(data, element, defaultTpl){
			if(data.type == 'state') return $('.issue-state.hidden:eq(0)').get(0).outerHTML;
			if(data.type == 'assignation') return $('.issue-assignation.hidden:eq(0)').get(0).outerHTML;
			if(data.type == 'tag') return $('.issue-tag.hidden:eq(0)').get(0).outerHTML;
			return defaultTpl;
		},
		showing : function(item,i){
			item.css({
				transform:'scale(0)',
				transition:'all 0.2s ease-in-out',
				opacity : 0
			}).removeClass('hidden');
			setTimeout(function(){
				item.css({
					transform:'scale(1)',
					opacity : 1
				})
			},(i+1)*10);
		}
	},function(response){
		$('.comment-message [data-mention-type="object"]').each(function(i,element){
			element = $(element);
			element.html('<a href="index.php?module=issue&page=sheet.report&id='+element.attr('data-mention-value')+'">#'+element.attr('data-mention-value')+'</a>')
		});
		isProcessing = false;
		if(callback!=null) callback();
	});
}

//Ajout ou modification d'élément issueevent
function issue_issue_event_save(element){
	if(isProcessing) return;
	var sendButton = $(element);
	var btnContent = sendButton.html();
	var data = $('#issue-event-form').toJson();
	data.issue = $('#issuereport-form').attr('data-id');

	sendButton.html('<i class="fas fa-pulse fa-spinner"></i> Envoi en cours').addClass('disabled').attr('disabled',true);
	isProcessing = true;

	$.action(data,function(r){
		$('#issue-event-form').attr('data-id','');
		$('#content').trumbowyg('html','');

		$('#event-files').val('').attr('data-data','{"id":-1}');

		isProcessing = false;

		issue_issue_event_search();
		$.message('success','Enregistré');
		sendButton.html(btnContent).removeClass('disabled').removeAttr('disabled');

		init_components('#issue-event-form');
	}, function(r){
		isProcessing = false;
		sendButton.html(btnContent).removeClass('disabled').removeAttr('disabled');
	});
}

//Récuperation ou edition d'élément issueevent
function issue_issue_event_edit(element){
	if(isProcessing) return;
	var line = $(element).closest('.issue-event');

	isProcessing = true;
	$.action({
		action:'issue_issue_event_edit',
		id:line.attr('data-id')
	},function(r){
		$.setForm('#issue-event-form',r);

		$('#event-files').attr('data-data',JSON.stringify({id:r.id}));

		$('#issue-event-form').attr('data-id',r.id);
		$('#content').trumbowyg('html',r.content);

		isProcessing = false;
		init_components();
		window.location = '#issue-event-form';
	},function(r){
		isProcessing = false;
	});
}

//Suppression d'élement issueevent
function issue_issue_event_delete(element){
	if(isProcessing) return;
	if(!confirm('Êtes vous sûr de vouloir supprimer ce commentaire ?')) return;
	var line = $(element).closest('.issue-event');

	if($('.issue-events .issue-comment:visible').length == 1){
		if(!confirm('Si vous supprimez le dernier commentaire, l\'intégralité du rapport sera supprimé')) return;
	}

	isProcessing = true;
	$.action({
		action: 'issue_issue_event_delete',
		id: line.attr('data-id')
	},function(r){
		isProcessing = false;
		line.css({
			transform: 'translateY(-100px)',
			opacity: 0
		});
		setTimeout(function(){
			line.remove();
			if(r.redirect) window.location = r.redirect;
		},300);
	},function(r){
		isProcessing = false;
	});
}