<?php namespace AloVoice; ?>
<center>
	<h3 class="h3 card-body">Записи для звонков</h3>
	<a href="#" onClick="addNewSoundAccount()" data-toggle="modal" data-target="#alvModal" class="btn btn-primary title_line_button"><i class="fa fa-telegram"></i>+ Добавить запись</a>
</center>

<style>
	.alv_table_lines .nowrp {
		white-space: nowrap;
	}
	.loadingline{
		display:none;
	}
</style>
<table class="table" id="stats_block_table">
	<thead>
		<tr id="alvsounds_table_header"></tr>
	</thead>
	<tbody id="alvsounds_table_body"> </tbody> 
</table>

<script>
//-lg

var afterLoadPage = function(){
	var isHeadered = false;
	loadAloVoiceInfo("alovoice_sounds_list",function(res){
			console.log("AloVoice Sounds RES:",res);
			window.alovoiceallsounds = res.datas;
			window.alovoiceallsoundsheaders = res.headers;
			window.soundspath = res.path;
			if(!isHeadered){
				if(typeof res.headers != 'undefined' ){
					isHeadered = true;
					$("#alvsounds_table_header").html('');
					
					$.each( res.headers, function( key, value ) {					
						console.log("Each Header:",key, value);
						$("#alvsounds_table_header").append('<th id="hd_'+key+'">'+value+'</th>');
					});
				}
			}
			
			if(typeof res.datas != 'undefined' ){
				$("#alvsounds_table_body").html('');
				$.each( res.datas, function( skey, sound ) {
					sound['id'] = skey;
					sound['link'] = window.soundspath + sound.name;
					$("#alvsounds_table_body").append(makeLineHtml(sound));
				});
				
				setTimeout(makePlayers,500);
			}

		});
		
}

function makePlayers(sid){
	var elm = (typeof sid != 'undefined') ? sid : '.mp3player';
	$(elm).css({width:'16px',height:'17px',margin:'3px 8px'});
	$(elm).each(function(){
		var filePath = $(this).attr('data-file');
		var m = new Microne(this);
		m.source(filePath);
	});
}

function makeLineHtml(sound){
	console.log("Each Sound:",sound);
	var lineHTML = '<tr class="alv_table_lines" id="trk_line_'+sound.id+'" data-title="'+sound.title+'">';
	
	$.each( window.alovoiceallsoundsheaders, function( hkey, hvalue ) {
		var lineclass= 'nowrp';
		if(hkey=="actions"){
			lineclass = 'nowrp d-flex flex-row pos-relative';
			var fileExt = (typeof sound.ext != ' undefined') ? sound.ext : sound.name.slice(-3);
			var value = '<div class="mp3player" id="snd_plr_'+sound.id+'" data-file="'+window.soundspath + sound.time+'.'+fileExt+'"></div>';
			value += '<a href="#" onClick="deleteOneSound(\''+sound.id+'\');"><i class="fa fa-trash"></i> Удалить</a>';
		} else if(hkey=="size") {
			var value = formatBytes(sound.size);
		} else if(hkey=="time") {
			var value = new Date(sound.time * 1000).toISOString().slice(0, 19).replace('T', ' ');
		} else if(hkey=="id") {
			var value = sound.id;
		} else {
			var value = sound[hkey];
		}
		
		lineHTML += '<td class="'+lineclass+'" > '+value+'</td>';
	});
	lineHTML += '</tr>';
	
	return lineHTML;
}

function deleteOneSound(fileid){
	console.log("Begin deleting:",fileid, window.alovoiceallsounds[fileid]);
	aloModal({
		label: "Удаления записи...",
		body: '<br> <h3>Вы точно хотите удалить запись: ['+window.alovoiceallsounds[fileid]['title']+']</h3>',
		btn: "Удалить",
		nohide: true,
		callback: function(){
			console.log("START deleting:",fileid, window.alovoiceallsounds[fileid]);

			loadAloVoiceInfo({"restmethod":"deletealovoiceonesound","fileid":fileid},function(res){
				console.log("Del RES: ",res);
				if(typeof res.deleted != 'undefined'){
					$("#trk_line_"+res.deleted).remove();
					$("#modalCloseBtn").click();
				}
			});
			
		}
	});
}

function addNewSoundAccount(){
	// var confcodesent = false;
	console.log("Begin adding snd........");
	aloModal({
		label: "Добавить запись",
		body: '<br> <form>'
			
			+'<div class="form-group">'
			+'<input type="text" class="form-control" id="alv_sound_name" placeholder="Введите названия для записи">'
			+'</div>'
			
			+'<div class="form-group">'
			+'<label for="alv_sound_file" class="btn btn-primary afilelabel">Выберите файл записи - *.mp3</label>'
			+'<input type="file" class="sound-file-input myfileinput" id="alv_sound_file" name="alv_sound_file" required accept=".mp3" onChange="doUpload(this)">'
			+'</div>'
			
			+'</form>',
		btn: "Отправить",
		nohide: true,
		callback: function(){
			// $("#tgaddformlabel").text("Введите код подтверждения:");
			// $("#tgnumber").val("").attr("id","tgnumbercode");
			//$("#modalCloseBtn").click();
			
			var soundName = $("#alv_sound_name").val();
			if(!soundName){ alert("No Name sound"); return true; }
			
			
			var saveElements = window.uploadedarfile;
			
			loadAloVoiceInfo({
				"cmd": "addNewMohFile",
				"arfile": window.uploadedarfile,
			},function(res){
				console.log("Save RES MOH: ",res);
				if(typeof res != 'undefined' && res){
					saveElements["restmethod"] = "savealovoiceonesound";
					saveElements["title"] = soundName;
					saveElements["moh_id"] = res;
					
					loadAloVoiceInfo(saveElements,function(res){
						console.log("Save RES: ",res);
						if(typeof res.time != 'undefined'){
							res["id"] = res.time;
							res['link'] = window.soundspath + res.name;
							$("#alvsounds_table_body").append(makeLineHtml(res));
							setTimeout(function(){makePlayers('#snd_plr_'+res.time)},500);
							$("#modalCloseBtn").click();
						}
						// $("#alv_settings_form").prepend('<div class="alert alert-success" id="savesuccesbox" role="alert">Настройки сохранены!</div>');
						// setTimeout(function(){
							// $("#savesuccesbox").remove();
						// },3000);
					});
					
				}
			});


		}
	});
	
}
</script>