// definition des fonctions de traitement des fichiers
/**
 * @todo : Convert these functions to a class object
 */


// Function used to find the linenumbers in the recipe file
// return an array of the lines numbers extracted from data

function finding_iteration_line_number (data) 
{
  
    var output = [];
  
    for (var i = 0, j = data.length; i < j; i++) {
    
        output[i] = data[i][1];
    
    }
  
    return output;
  
}

/*
****************************************************************************************************************************
** function finding_matches_in_file (Originalfile, pattern)
** This function id used to find all the matches of a pattern in a file
**
** retrune the array of all the pattern and the line and more
** array 2D
**
** Obsolete function , it is replaced by the function str.matchAll(RegEx)
**
****************************************************************************************************************************
*/

function finding_matches_in_file (Originalfile, pattern)
{
    var j = 1;
    var match_file = [];
    var matches = [];
                
    while (matches_file) 
    {
        matches[j] = matches_file[2];

        if(matches[2].length === 0) 
        {
            break;
        }
        ++j;
        match_file = patterns[pattern].exec(Originalfile);
    }

    return matches;
}

// **************************************************************************************************************************
// function sum_plasma_duration ($data,$sourceON, $sourceOFF)
// Function used to sum the duration between Source ON and the following Source OFF
// And Format the duration to HH:MM:SS on return value
// tghe format is done by using the PHP object DateInterval
// 
// Autre cas particulier: le temps de process doit être converti dans le format (H)H:MM(:SS)
// On additionne les temps trouvés dans la recette compris entre source on et source off et on convertit dans le bon format
// l'utilisateur finit de le modifier si nécessaire.
// **************************************************************************************************************************


function sum_plasma_duration(data,sourceON, sourceOFF) 
{
  
    var totaltime = 0;
      
    for(var a = 0, b = sourceON.length; a < b; a++) 
    {
          
        for(var c = 0, d = data.length; c < d; c++) 
        {
        
            if( (parseFloat(data[c][1])>parseFloat(sourceON[a])) && (parseFloat(data[c][1])<parseFloat(sourceOFF[a])) ) 
            //oblige de convertir les chaines de caractère en nombre pour comparer des nombres en tant que numéro de ligne
            {
          
                totaltime = totaltime + parseFloat(data[c][2]);
            
            }
        
        }
      
    }

    return ('PT'+totaltime+'S');
    
}


// **************************************************************************************************************************
// function parse_icpsentech($filecontent)
// 
// Function parsing the input data which are the recipe
// the parsing code seems compatible for both Sentech SI500 and SI500S
// 
// ****************************************************************************************************************************


function parse_icpsentech(file, RecipeName) 
{
  
    var matches_out = [];
    var outarray = {};
    var PowerON_lines = [];
    var PowerOFF_lines = [];
    
    if(!file.match(/Filetype=SENTECH Instruments SI/)) 
    {
    
        throw new Error 
        (
                "Bad recipe file format"
        )
        
    }
    
    if(matches_out === 0) 
    {
    
        return false;
    
    }
    
	if (operationType!="process")
	{
		throw new Error("operationType must be process");
	}

    var patterns = 
    {

        "temperature"                   : /(\S*)\=Electrode temperature\s([0-9,]*).*\s\n/g,
        "Gas"                           : /(\S*)\=Start gas.* MFC.* (\S*).* sccm ' (\S*)\s+/g,
        "pressure"                      : /(\S*)\=Pressure reactor\s(.*)\s\n/g,
        "biasvoltage"                   : /(\S*)\=RF generator on bias\s(.*)\s\n/g,
        "PBias"                         : /(\S*)\=RF generator on power\s(.*)\s\n/g,
        "picp"                          : /(\S*)\=Source on\s(.*)\s\n/g,
        "PICP_Off"                    : /(\S*)\=Source off\s\n/g,
        "P_Off"                         : /(\S*)\=Stop plasma sources.*\s\n/g,
        "etchingTime"   		    : /(\S*)\=Waiting period\s(.*)\s\n/g,

    }
            
    for(var key in patterns) 
	{ // pour chaque clef du tableau pattern

        var matches_out = [...file.matchAll(patterns[key])]; // on récupère dans un tableau toutes les occurences correspondant au regEx sur le fichier
    
        // on regarde si on trouve le contenu dans le fichier
        if (matches_out.length>0) 
	    {
            
            // si oui on recupere la valeur qui nous interresse c'est a dire celle dans le () dans
            // l'expression pour la stocker dans une variable de type string.
            // remarque preg_replace peut travailler directement sur un array
            // implode permet de concatener tout les elements d'un array en les separant par une chaine
            
            
            // cas particulier des gas
            // il faut créer autant d'items qu'il y a de lignes de gaz utilisées
            // ainsi on retournera Gas 1, Gas 2, etc.

	    

            if(key === "Gas") 
		    {

                for (var i=0, j=matches_out.length; i<j; i++)
                {
                    outarray["gas" + (i+1)] = matches_out[i][3]; //Permet de récupérer le nom du gaz

                    outarray["flowGas" + (i+1)] = parseFloat(matches_out[i][2].replace(',', '.'));
                     // Permet de récupérer le flux du gaz plus conversion de la virgule en point
                     // cette virgule provient de la langue utilisée sous windows ou sous le logiciel
                     // Normalement, peut être laissé même sur un poste anglais puisque pas de conversion si absence de ','

                
                }                 
                
            }

            else if(key === "temperature") 
	        {
                
                outarray[key] = parseFloat(matches_out[0][2].replace(',', '.'));
                
            }

            else if(key === "pressure") 
	        {
                outarray[key] = parseFloat(matches_out[0][2].replace(',', '.'));

            }

            else if(key === "biasvoltage") 
		    {

                outarray[key] = parseFloat(matches_out[0][2].replace(',', '.'));

            }

            else if(key === "pBias") 
		    {
                    
                outarray["pBias"] = parseFloat(matches_out[0][2].replace(',', '.'));

		    }
           
            else if(key === "picp") 
		    {   
                
                outarray["picp"] = parseFloat(matches_out[0][2].replace(',', '.'));
                PowerON_lines = finding_iteration_line_number(matches_out);

                    
            }
                
            else if(key === "PICP_Off") 
		    {
                    
                PowerOFF_lines = finding_iteration_line_number(matches_out);
                    
            }

            else if(key === "P_Off") 
		    {

                PowerOFF_lines = finding_iteration_line_number(matches_out);
                    
            }
                
            else if(key === "etchingTime") 
		    {

                outarray["runningTime"] = sum_plasma_duration(matches_out, PowerON_lines, PowerOFF_lines);

            }
            
        }
  
    }
    
    outarray["recipename"] = RecipeName;
    console.log(outarray);
    return outarray;
  
}

return parse_icpsentech(fileContent, fileName);