// *******************************************
// Title: Receiving - Auto-Assign Work Orders
// Author: Fluke Calibration
// Date: 2017-05-19
//
// This data check will assign work orders
// to technicians based on the Work Area field
// defined on the asset's type.
// *******************************************

/*
SQL Function: getUsers

SELECT nUserUID, cUsername
FROM Users
WHERE lActive <> 0 AND lDeleted = 0
*/

// This variable contains the map between MET/TEAM
// user names and the disciplines they are responsible for.
// Note that a user can be associated with more than one discipline.
// The disciplines should match the entries in the Types.cArea
// drop down list.
var tech = [
    {username:'Admin', discipline:'Electronic'},
    {username:'Admin', discipline:'Pressure'},
    {username:'User', discipline:'Mechanical'}
];

var matchFound = false;

// Get the Work Area value
var cArea = Model.cArea;

// Iterates through the tech variable, comparing with cArea
for (var i = 0; i < tech.length; i++) {
    
    // If a match is found, set the flag and call the setAssignedTech() function
    if (cArea.toLowerCase() == tech[i].discipline.toLowerCase()) {
        matchFound = true;
        setAssignedTech(tech[i].username);
        break;
    }
}

// If a match was not found, process the record. If a match is found, the pass
// status is provided within the setAssignedTech() function.
if (matchFound == false) {
    pass();
}


function setAssignedTech(nameParam) {
    DataCheck.ExecuteSQL('getUsers', function(result) {
        
        // Compare the provided username with the list of usernames in the DB
        for (var j = 0; j < result.length; j++) {
            
            // If a match is found, update the cached memory on the page with
            // an explicit Assigned Technician value
            if (result[j].cUsername.toLowerCase() == nameParam.toLowerCase()) {
                
                $.ajax({
                    url:'/Receiving/UpdateMemoryCallSheet/',
                    type: 'post',
                    data: 'nAssetUID=' + Model.nAssetUID + '&nAssignedTechUID='
                        + result[j].nUserUID,
                    async: false
                });
                
                pass();
                return;
            }
        }

        // If a matching user in the DB is not found, process anyways
        pass();
    });
}