var user_idx = 0;

/**
 * funtion add new line to html table
 */

function addNewUserLine() {
    $('#user-table-body').append(
        '<tr id="tr_user'+user_idx+'" class="new_user">'+
        '<td><input type="checkbox" id="user_check'+user_idx+'" class="user_check" value="'+user_idx+'" name="user_chk[]"></td>' +
        '<td><input type="text" id="user_name'+user_idx+'" class="form-control user_name"></td>'+
        '<td><input type="text" id="user_full_name'+user_idx+'" class="form-control user_full_name" value=""></td>'+
        '<td><select type="text" id="user_group'+user_idx+'" class="form-control user_option" style=>'+
            '<option hidden>Choose User Group</option>'+
            $('#cobusergroup').html() +
        '</select></td>'+
        '<td style="display:none" class="user_id" id="user_id'+user_idx+'">-1</td>'+
        '<td style="display:none" class="user_idx" id="user_idx'+user_idx+'">'+user_idx+'</td>'+
        '</tr>'
    );
    user_idx++;
}
/**
 * funtion save table value to database
 * callback to onResponseUserEntry()
 */
function saveUser() {
    LoadingScreen("show");

    if( validateUser() ){
        var data = { 
                 "type"         : C_ADD,
				 "index"        : screen_index,
                 "new_user"     : getNewUserTable(),
                 "existing_user": getUserTable()
				};
        var url  = "index.pzx?c=" + user_url + "&d=" + new Date().getTime() ;
		callServer(url,"json",data,onResponseUserEntry,null) ;
		return false;
    }else{
        LoadingScreen("hide");
        swal.fire('Warning',"Please fill all description",'warning');
    }
}

/**
 * funtion get table value 
 * return json array
 */
function getNewUserTable() {
    var arrays = [];
    $('#user-table-body tr.new_user').each(function() { 
		var idx = $('.user_idx',this).html() ;
        var data = {     
			"user_id"   : $('.user_id',this).html() ,
			"name"      : $(".user_name",this).val(),
			"full_name" : $(".user_full_name",this).val(),
            "user_group": $(".user_option",this).val(), 	
        };   
        arrays.push(data);
    }); 
    if(arrays == ""){
        return "";
    }else{
        return JSON.stringify(arrays) ;
    }
    
}

function getUserTable() {
    var arrays = [];
    $('#user-table-body tr.existing_user').each(function() { 
		var idx = $('.user_idx',this).html() ;
        var data = {     
			"user_id"   : $('.user_id',this).html() ,
			"name"      : $(".user_name",this).val(),
			"full_name" : $(".user_full_name",this).val(),
            "user_group": $(".user_option",this).val(),  	
        };   

        arrays.push(data);
    }); 
    return JSON.stringify(arrays) ;
}

/**
 * funtion validate data
 * check if have empty value on the table
 * return boolean
 */
function validateUser() {
    var allstatus = true;
    $('#currency-master-table-body tr').each(function() { 
		var desc = $(".user_desc",this).val();
        if(desc=="" || desc==undefined){
            
            allstatus = false;
        }

    }); 

    return allstatus;    
}

/** 
 * amend all field to be edited
*/
function amendUserLine() {
    $('.user_check').prop('disabled',false);
    $('.user_full_name').prop('disabled',false);
    $('.user_option').prop('disabled',false);
}

/**
 * delete record on table
 * check if id value = -1
 * if not have to remove from database first
 */
function resetUserPassword() {
    var lines = [];
	$("input[name='user_chk[]']:checked").each(function(i){
		lines[i] = $(this).val();
	});
  
    //confirmation and delete column
	if(lines.length > 0) {
		if(lines === null || lines === undefined || lines.length === 0) {
			swal.fire("Error", "No selected user to reset password", "error");
			return;
		}
		
		swal.fire({
			title: "System Confirmation",
			text: "Are you sure you want to reset the password of selected user?",
			icon: "warning",
			showCancelButton: true,
			confirmButtonColor: "#3085d6",
			cancelButtonColor: "#d33",
			confirmButtonText: "Yes"
		})
		.then(function(result) {
			if(result.value) {
				var arrays = [];
				var count = 0;
				for(var i = 0; i < lines.length; i++) {
					if($('#user_id'+lines[i]).html() === null || $('#user_id'+lines[i]).html() === undefined || $('#user_id'+lines[i]).html() === "-1") {
						count++;
					} else {
						arrays.push($('#user_id'+lines[i]).html());
					}
				}
			
				if(arrays.length > 0) {
					LoadingScreen("show");
					var data = { "type": C_CHANGE, "id": JSON.stringify(arrays), "index":screen_index };		
					var url  = "index.pzx?c=" + user_url + "&d=" + new Date().getTime() ;
					callServer(url,"json",data,onResponseUserEntry,null) ;
				} else if(count > 0) {
					swal.fire("warning", "Selected user hasnt been saved into database");
				}
            }
		});
	} else {
		return;
    }
}

function deleteUserLine() {
    var lines = [];
	$("input[name='user_chk[]']:checked").each(function(i){
		lines[i] = $(this).val();
	});
  
    //confirmation and delete column
	if(lines.length > 0) {
        swal.fire({
			title: "System Confirmation",
			text: "Are you sure you want to delete the selected record?",
			icon: "warning",
			showCancelButton: true,
			confirmButtonColor: "#3085d6",
			cancelButtonColor: "#d33",
			confirmButtonText: "Yes",
		})
		.then(function(result) {
			if(result.value) {
				var arrays = [];
				for(var i = 0; i < lines.length; i++) {
					if($('#user_id'+lines[i]).html() === null || $('#user_id'+lines[i]).html() === undefined || $('#user_id'+lines[i]).html() === "-1") {
                        $('#tr_user'+lines[i]).remove();
					} else {
						arrays.push($('#user_id'+lines[i]).html());
					}
				}
			
				if(arrays.length > 0) {
                    LoadingScreen("show");
                    var data = { "type": C_DELETE, "id": JSON.stringify(arrays), "index":screen_index };		
                    var url  = "index.pzx?c=" + user_url + "&d=" + new Date().getTime() ;
                    callServer(url,"json",data,onResponseUserEntry,null) ;
				}
            }
		});
	} else {
		return;
    }
}

/**
 * get analysis setting record/ filter
 * callback to onResponseUserEntry()
 */
function userFilter() {    
    LoadingScreen("show");
    var data = { "type": C_LIST,
				 "index": screen_index,
                 "sorts": sorts,
				};
    var url  = "index.pzx?c=" + user_url + "&d=" + new Date().getTime() ;
	callServer(url,"json",data,onResponseUserEntry,null) ;
}

/**
 * response callback from above function
 */
function onResponseUserEntry(obj,resp) {
    LoadingScreen("hide");
    if(resp.status!=C_OK){
		swal.fire('Warning',resp.mesg,'warning');
		return;
	}
    if(resp.type == C_ADD){
        swal.fire('Success',resp.mesg,'success');
        userFilter();
    }else if(resp.type == C_LIST){
        
        $('#user-table-body').html(resp.data.html);
        user_idx = resp.data.idx;
        
    }else if(resp.type == C_DELETE ){
        swal.fire('Success',resp.mesg,'success');
        userFilter();
    }else if(resp.type == C_CHANGE ){
        swal.fire('Success',resp.mesg,'success');
    }
}