<commit_before>'use strict';
angular.module('com.module.protocols')
  .controller('ProtocolsCtrl', function($http,$scope, $state, $stateParams, CoreService,
    FormHelper, gettextCatalog, Protocol, ProtocolsService, $rootScope,Bioportal,$timeout,ProtocolUsage,LoopBackAuth) {


$scope.user=LoopBackAuth.currentUserData;
$scope.isadmin=$rootScope.isadmin;
$scope.autocompleteResults=[];
$scope.protocolUsage={};
$scope.evidence={};

var BioportalSplitter=".";
var CategorySplitter="_";
var SpaceSplitter="0";
  
//retrieve protocol model
$scope.requiredProps=[];
$scope.schemaProps={};
$scope.formProps=[];


  /*USEFUL HELPERS*/
$scope.capFirst=function(str) { return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();}); }
var propname=function(str){
  return $scope.capFirst(str.split(CategorySplitter)[1]||" ");
};  
var catname=function(str){
  return $scope.capFirst(str.split(CategorySplitter)[0]||" ");
};
$scope.cName=catname;
$scope.pName=propname;
$scope.arrayNames=function(arr){
  console.log(arr);
  if(arr instanceof Array) return arr.map(function(val){
    return bName(val);
  }).join(", ");
  else return bName(arr);
}


//autocomplete fetch from bioportal
$scope.bioportalAutocomplete = function(search,field) {
  if(search.length>2){
    $scope.loading = true;
  Bioportal.autocomplete(search,field.templateOptions.bioportal)
  .then(function(res){
    $scope.loading=false;
    var list=res.data.collection;
    if(list.length<1) {
      list.push({
        cui:[Math.random()*1000,0],
        prefLabel:search
      });
    }    
    $scope.autocompleteResults=field.templateOptions.options=list.map(function(obj){

        var id=obj['cui'][0]; 
        var link=(obj['id']||obj['@id']); 
        return { 
          "label": obj.prefLabel, 
          "id": id,
          "link":link
        };
    });
  },function(err){console.log(err);});
  }
};

//autocomplete for pubmed
$scope.searchPubmed = function(search) {
  var newsearch=search;
  if($scope.evidence.exactPubMedSearch) newsearch='"'+search+'"';
  if(search.length>4||$scope.evidence.exactPubMedSearch){
    $scope.loading = true;
    return $http.jsonp(
      'http://www.ebi.ac.uk/europepmc/webservices/rest/search/query='+newsearch
      +'&resulttype=lite&format=json&callback=JSON_CALLBACK'
    ).then(function(response) {
        $scope.loading = false;
      var list=response.data.resultList.result;
      if(list.length<1) {
        list.push({
          title:"No results"
        });
      }
      $scope.pubmedResults = list;
      });
  }
};

/*OUTCOMES*/
$scope.outcome={};
$scope.outcome.types=["primary","secondary","other"];
$scope.addOutcome=function(item,model){
  if(!$scope.protocol.outcomes) $scope.protocol.outcomes=[];
  var itemExist=false;
  for (var i=0,l=$scope.protocol.outcomes.length;i<l;i++){
    if(item.id===$scope.protocol.outcomes[i].id) {
      itemExist=true;
      break;
    }
  }
  if(!itemExist){
    item.type=""+$scope.outcome.selectedType;
    $scope.protocol.outcomes.push(item);
  }
};
$scope.removeOutcome=function(index){
  $scope.protocol.outcomes.splice(index,1);
};

/*Evidence*/
$scope.addPubmedArticle=function(item,model){
  $scope.pubmedResults=[];
  if(!$scope.protocol.evidences) $scope.protocol.evidences=[];
  var itemExist=false;
  if(!item.pmid) return false;
  for (var i=0,l=$scope.protocol.evidences.length;i<l;i++){
    if(item.pmid===$scope.protocol.evidences[i].pmid) {
      itemExist=true;
      break;
    }
  }
  if(!itemExist){
    $scope.protocol.evidences.push({
      "title":item.title,
      "pmid":item.pmid,
      "authorString":item.authorString,
      "pubYear":item.pubYear
    });
  }
};
$scope.removePubmedArticle=function(index){
  $scope.protocol.evidences.splice(index,1);
};


var findParent=function(parentId){
    Protocol.findById({
        id: parentId
    }, function(protocol) {
        $scope.protocolParent=protocol;
    });
};




/*Logical expression builder */

function repeat(pattern, count) {
    if (count < 1) return '';
    var result = '';
    while (count > 1) {
        if (count & 1) result += pattern;
        count >>= 1, pattern += pattern;
    }
    return result + pattern;
}

function htmlEntities(str) {
    return String(str).replace(/</g, '&lt;').replace(/>/g, '&gt;');
}

function computed(group,nested,next) {
    nested++;
    if (!group) return "";
    for (var str = "", i = 0; i < group.rules.length; i++) {
        i > 0 && (str += " ");
        // (group.rules[i].group.rules.length>1?")":"") 
        str += group.rules[i].group ?" <br> "+repeat('&nbsp;',nested*8)+
            (group.rules[i].group.rules.length>1?"( ":"") +
            " <br> "+repeat('&nbsp;',(nested+1)*8)+
            computed(group.rules[i].group,nested,group.rules[i+1]) +"<br>"+repeat('&nbsp;',nested*8)+ 
            (group.rules[i].group.rules.length>1?") ":"") +
            (group.rules[i+1]?" <strong>" + group.operator + "</strong> ":"")
            :
            "<a href='"+group.rules[i].field.selected.link+"' target='_blank'>"+
            group.rules[i].field.selected.label + 
            "</a>"+
            (group.rules[i].hasValue?
            " <span class='le-operator label label-primary'>"+
            htmlEntities(group.rules[i].condition) + "</span> " + 
            group.rules[i].data+
            " <a href='"+group.rules[i].unit.selected.link+"' target='_blank'>"+
            group.rules[i].unit.selected.label + 
            "</a>"
            :"")+
            (i!==(group.rules.length-1)?" <strong>" + group.operator + "</strong>":"");
    }

    return str;
}

$scope.$watch('filter', function (newValue) {
    $scope.protocol.initial_expression.data = newValue;
    $scope.protocol.initial_expression.label=$scope.output = computed(newValue.group,0,{});
}, true);



/*CHECK FOR PROTOCOL ID or EDIT/VIEW/LIST*/

var protocolId=$stateParams.id||$stateParams.parentId||'';
if ( protocolId.length===24 ) {
  <commit_msg>improve format at expression builder<commit_after>'use strict';
angular.module('com.module.protocols')
  .controller('ProtocolsCtrl', function($http,$scope, $state, $stateParams, CoreService,
    FormHelper, gettextCatalog, Protocol, ProtocolsService, $rootScope,Bioportal,$timeout,ProtocolUsage,LoopBackAuth) {


$scope.user=LoopBackAuth.currentUserData;
$scope.isadmin=$rootScope.isadmin;
$scope.autocompleteResults=[];
$scope.protocolUsage={};
$scope.evidence={};

var BioportalSplitter=".";
var CategorySplitter="_";
var SpaceSplitter="0";
  
//retrieve protocol model
$scope.requiredProps=[];
$scope.schemaProps={};
$scope.formProps=[];


  /*USEFUL HELPERS*/
$scope.capFirst=function(str) { return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();}); }
var propname=function(str){
  return $scope.capFirst(str.split(CategorySplitter)[1]||" ");
};  
var catname=function(str){
  return $scope.capFirst(str.split(CategorySplitter)[0]||" ");
};
$scope.cName=catname;
$scope.pName=propname;
$scope.arrayNames=function(arr){
  console.log(arr);
  if(arr instanceof Array) return arr.map(function(val){
    return bName(val);
  }).join(", ");
  else return bName(arr);
}


//autocomplete fetch from bioportal
$scope.bioportalAutocomplete = function(search,field) {
  if(search.length>2){
    $scope.loading = true;
  Bioportal.autocomplete(search,field.templateOptions.bioportal)
  .then(function(res){
    $scope.loading=false;
    var list=res.data.collection;
    if(list.length<1) {
      list.push({
        cui:[Math.random()*1000,0],
        prefLabel:search
      });
    }    
    $scope.autocompleteResults=field.templateOptions.options=list.map(function(obj){

        var id=obj['cui'][0]; 
        var link=(obj['id']||obj['@id']); 
        return { 
          "label": obj.prefLabel, 
          "id": id,
          "link":link
        };
    });
  },function(err){console.log(err);});
  }
};

//autocomplete for pubmed
$scope.searchPubmed = function(search) {
  var newsearch=search;
  if($scope.evidence.exactPubMedSearch) newsearch='"'+search+'"';
  if(search.length>4||$scope.evidence.exactPubMedSearch){
    $scope.loading = true;
    return $http.jsonp(
      'http://www.ebi.ac.uk/europepmc/webservices/rest/search/query='+newsearch
      +'&resulttype=lite&format=json&callback=JSON_CALLBACK'
    ).then(function(response) {
        $scope.loading = false;
      var list=response.data.resultList.result;
      if(list.length<1) {
        list.push({
          title:"No results"
        });
      }
      $scope.pubmedResults = list;
      });
  }
};

/*OUTCOMES*/
$scope.outcome={};
$scope.outcome.types=["primary","secondary","other"];
$scope.addOutcome=function(item,model){
  if(!$scope.protocol.outcomes) $scope.protocol.outcomes=[];
  var itemExist=false;
  for (var i=0,l=$scope.protocol.outcomes.length;i<l;i++){
    if(item.id===$scope.protocol.outcomes[i].id) {
      itemExist=true;
      break;
    }
  }
  if(!itemExist){
    item.type=""+$scope.outcome.selectedType;
    $scope.protocol.outcomes.push(item);
  }
};
$scope.removeOutcome=function(index){
  $scope.protocol.outcomes.splice(index,1);
};

/*Evidence*/
$scope.addPubmedArticle=function(item,model){
  $scope.pubmedResults=[];
  if(!$scope.protocol.evidences) $scope.protocol.evidences=[];
  var itemExist=false;
  if(!item.pmid) return false;
  for (var i=0,l=$scope.protocol.evidences.length;i<l;i++){
    if(item.pmid===$scope.protocol.evidences[i].pmid) {
      itemExist=true;
      break;
    }
  }
  if(!itemExist){
    $scope.protocol.evidences.push({
      "title":item.title,
      "pmid":item.pmid,
      "authorString":item.authorString,
      "pubYear":item.pubYear
    });
  }
};
$scope.removePubmedArticle=function(index){
  $scope.protocol.evidences.splice(index,1);
};


var findParent=function(parentId){
    Protocol.findById({
        id: parentId
    }, function(protocol) {
        $scope.protocolParent=protocol;
    });
};




/*Logical expression builder */

function repeat(pattern, count) {
    if (count < 1) return '';
    var result = '';
    while (count > 1) {
        if (count & 1) result += pattern;
        count >>= 1, pattern += pattern;
    }
    return result + pattern;
}

function htmlEntities(str) {
    return String(str).replace(/</g, '&lt;').replace(/>/g, '&gt;');
}
function groupExist(rules){
    for (var obj in rules) {
        if(obj==='group') return true;
    }
    return false;
}

function computed(group,nested,next,parent) {
    nested++;
    if (!group) return "";
    if (!parent) parent=group;
    for (var str = "", i = 0; i < group.rules.length; i++) {
        i > 0 && (str += " ");
        // (group.rules[i].group.rules.length>1?")":"") 
        // (simple?"":" <br> "+repeat('&nbsp;',(nested+1)*8))+
        str += 
            group.rules[i].group ?" <br> "+repeat('&nbsp;',nested*8)+
                (group.rules[i].group.rules.length>1?"( ":"") +
                
                computed(group.rules[i].group,nested,group.rules[i+1],group)+
                (parent.rules[parent.rules.length-1].group?"":"<br>"+repeat('&nbsp;',nested*8))+ 
                
                (group.rules[i].group.rules.length>1?") ":"") +
                (group.rules[i+1]?" <strong>" + group.operator + "</strong> ":"")
            :
            "<a href='"+group.rules[i].field.selected.link+"' target='_blank'>"+
            group.rules[i].field.selected.label + 
            "</a>"+
            (group.rules[i].hasValue?
            " <span class='le-operator label label-primary'>"+
            htmlEntities(group.rules[i].condition) + "</span> " + 
            group.rules[i].data+
            " <a href='"+group.rules[i].unit.selected.link+"' target='_blank'>"+
            group.rules[i].unit.selected.label + 
            "</a>"
            :"")+
            (i!==(group.rules.length-1)?" <strong>" + group.operator + "</strong>":"");
    }

    return str;
}

$scope.$watch('filter', function (newValue) {
    $scope.protocol.initial_expression.data = newValue;
    $scope.protocol.initial_expression.label=$scope.output = computed(newValue.group,0,{});
}, true);



/*CHECK FOR PROTOCOL ID or EDIT/VIEW/LIST*/

var protocolId=$stateParams.id||$stateParams.parentId||'';
if ( protocolId.length===24 ) {
  
{'fraction_non_alphanumeric': 0.192245163388067, 'fraction_numerical': 0.006259144854495204, 'mean_word_length': 3.344279661016949, 'pattern_counts': {'":': 26, '<': 43, '<?xml version=': 0, '>': 49, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1887102', 'n_tokens_mistral': 4261, 'n_tokens_neox': 4150, 'n_words': 570}