// Task: PROF-53 | VIP-19, croja022 (add patent feature)
// Initial file creation with incomplete implementation.
// User Story: PROF-32 | VIP-19, enwam001 (patent search)
// Added initial full implementation
(function () {
  'use strict';

  var patentFunctions = PatentHelper();


  angular
      .module('patent')
      .controller('patentSearchController', patentSearchController);
      patentSearchController.$inject = ['DTOptionsBuilder', 'DTColumnBuilder','$sce', '$location', '$state', '$scope', '$stateParams', 'User', '$window'];
  /* @ngInject */
  var i = 0;
  var token;
  var valid_token = false;
  var search_type = "USPTO";
  function patentSearchController(DTOptionsBuilder, DTColumnBuilder, $sce, $location, $state, $scope, $stateParams, User, $window) {
  var vm = this;
  vm.done = false;
  vm.done = true;
  vm.query = "";
  vm.options = ['USPTO', 'EPO'];
  vm.selection = vm.options[0];
  var uspto_dtOptions = DTOptionsBuilder.fromSource('').withFnServerData(ServerData).withPaginationType('full_numbers').withOption('responsive', true).withPaginationType('full_numbers').withDataProp('patents').withOption('processing', true).withButtons([
    'colvis',        
    'print',                   
  ]);        
  var uspto_dtColumns = [    
    DTColumnBuilder.newColumn('patents').withTitle('Title').renderWith(function(data, type, full) 
     {
         if(search_type == 'USPTO')
         {
            if (full == null)
            return null;
            return full.patent_title;
         } else {
            if(Array.isArray(full['exchange-document'])){
                if (Array.isArray(full['exchange-document'][0]['bibliographic-data']['invention-title'])){
        
                  for(i = 0; i < full['exchange-document'][0]['bibliographic-data']['invention-title'].length; i++ )
                  {
                    if(full['exchange-document'][0]['bibliographic-data']['invention-title'][i]['@lang'] == "en")
                      return full['exchange-document'][0]['bibliographic-data']['invention-title'][i]['$']; 
                  }          
                } else{
                  return  full['exchange-document'][0]['bibliographic-data']['invention-title']['$']
                }      
              }  
        
              if (Array.isArray(full['exchange-document']['bibliographic-data']['invention-title'])){         
                for(i = 0; i < full['exchange-document']['bibliographic-data']['invention-title'].length; i++ )
                {
                  if(full['exchange-document']['bibliographic-data']['invention-title'][i]['@lang'] == "en")
                    return full['exchange-document']['bibliographic-data']['invention-title'][i]['$']; 
                }
              } else{
                return  full['exchange-document']['bibliographic-data']['invention-title']['$']
              }
         }

     }).withOption('defaultContent', '-default value-'),
     DTColumnBuilder.newColumn('patents').withTitle('Patent Number').renderWith(function(data, type, full) 
     {
        if(search_type == 'USPTO')
        {
            if (full == null)
            return null;
      
            return full.patent_number;
        } else {
            if(Array.isArray(full['exchange-document'])){
                return full['exchange-document'][0]['bibliographic-data']['application-reference']['document-id'][1]['doc-number']['$'];    
              }  
        
              return full['exchange-document']['bibliographic-data']['application-reference']['document-id'][1]['doc-number']['$'];
        }



     }).withOption('defaultContent', '-default value-'),
     DTColumnBuilder.newColumn('patents').withTitle('Abstract:').renderWith(function(data, type, full) 
     {
        if(search_type == 'USPTO')
        {
            if (full == null)
            return null;      
            return full.patent_abstract;
        } else {

            if(Array.isArray(full['exchange-document'])){

                if(Array.isArray(full['exchange-document'][0]['abstract']))
                {
                  return(full['exchange-document'][0]['abstract'][0]['p']['$'])
                }else{
                    if(full['exchange-document'][0]['abstract'] == undefined)
                    return null
                  return(full['exchange-document'][0]['abstract']['p']['$'])
                }      
              }  
        
              if(Array.isArray(full['exchange-document']['abstract'])){        
                for(i = 0; i < full['exchange-document']['abstract'].length; i++){
                  if(full['exchange-document']['abstract'][i]['@lang'] == "en"){
                  return(full['exchange-document']['abstract'][i]['p']['$']) 
                } else {return(full['exchange-document']['abstract'][0]['p']['$']) }
                } 
              }  
              if(full['exchange-document']['abstract'] == undefined )
              return null;
        
              return full['exchange-document']['abstract']['p']['$'];
        }


     }).withOption('defaultContent', '-default value-').withClass('none'),
    DTColumnBuilder.newColumn('patents').withTitle('Category:').renderWith(function(data, type, full) 
     {

    if(search_type == 'USPTO')
    {
        if (full == null)
        return null;
  
        return full.patent_type;
    }else {
        var category = [] 

        if(Array.isArray(full['exchange-document'])){
          if(full['exchange-document'][0]['bibliographic-data']['classifications-ipcr'] == undefined)
          return null;
        if(Array.isArray(full['exchange-document'][0]['bibliographic-data']['classifications-ipcr']['classification-ipcr'])){                
          for(i = 0; i < full['exchange-document'][0]['bibliographic-data']['classifications-ipcr']['classification-ipcr'].length; i++)
          {
            category.push(full ['exchange-document'][0]['bibliographic-data']['classifications-ipcr']['classification-ipcr'][i]['text']['$'] + ' ')
          }
  
           return category.toString();
        }      
        return full ['exchange-document'][0]['bibliographic-data']['classifications-ipcr']['classification-ipcr']['text']['$']
        }
  
     
    if (full ['exchange-document']['bibliographic-data']['classifications-ipcr']  == undefined)
    return null;

        if(Array.isArray(full['exchange-document']['bibliographic-data']['classifications-ipcr']['classification-ipcr'])){        
          for(i = 0; i < full['exchange-document']['bibliographic-data']['classifications-ipcr']['classification-ipcr'].length; i++)
          {
            
            category.push(full ['exchange-document']['bibliographic-data']['classifications-ipcr']['classification-ipcr'][i]['text']['$'] + ' ')
          }
           return category.toString();
        }  
  
        return full['exchange-document']['bibliographic-data']['classifications-ipcr']['classification-ipcr']['text']['$']
    }

     }).withOption('defaultContent', '-default value-').withClass('none'),
    DTColumnBuilder.newColumn('patents').withTitle('Date').renderWith(function(data, type, full) 
     {
        if(search_type == 'USPTO')
        {
            if (full == null)
            return null;
      
            return full.patent_date;
        } else {
            var date;
      
            if(Array.isArray(full['exchange-document'])){
              date = full['exchange-document'][0]['bibliographic-data']['application-reference']['document-id'][1]['date']['$'].substring(0, 4);
              date += '-' + full['exchange-document'][0]['bibliographic-data']['application-reference']['document-id'][1]['date']['$'].substring(4, 6);
              date += '-' + full['exchange-document'][0]['bibliographic-data']['application-reference']['document-id'][1]['date']['$'].substring(6, );
              return date;      
            }
      //error $ undefined
            date = full['exchange-document']['bibliographic-data']['application-reference']['document-id'][1]['date']['$'].substring(0, 4);
            date += '-' + full['exchange-document']['bibliographic-data']['application-reference']['document-id'][1]['date']['$'].substring(4, 6);
            date += '-' + full['exchange-document']['bibliographic-data']['application-reference']['document-id'][1]['date']['$'].substring(6, );
            return date;
        }


     }).withOption('defaultContent', '-default value-'),
    DTColumnBuilder.newColumn('patents').withTitle('Inventors').renderWith(function(data, type, full) 
    {
        if(search_type == 'USPTO'){

            if (full == null)
            return null;
       
            var inventor_names = "";
           if (full.inventors.length == 1)
           {
             inventor_names += full.inventors[0].inventor_first_name + "&nbsp" + full.inventors[0].inventor_last_name;
           } else 
           {
               for (i = 0; i < full.inventors.length - 1; i++) 
               {
                 inventor_names += full.inventors[i].inventor_first_name + "&nbsp" + full.inventors[i].inventor_last_name + ", ";
               }
               inventor_names += full.inventors[i].inventor_first_name + "&nbsp" + full.inventors[i].inventor_last_name;
             }
             return inventor_names;  
        } else {
            var inventor_names = "";
      
            if(Array.isArray(full['exchange-document'])){
              if (full['exchange-document'][0]['bibliographic-data'] == undefined){
                return null;
              }
                if (full['exchange-document'][0]['bibliographic-data']['parties']['inventors'] == undefined){
                return null;
              }
              
              if(!(Array.isArray(full['exchange-document'][0]['bibliographic-data']['parties']['inventors']['inventor'])))       
                return full['exchange-document'][0]['bibliographic-data']['parties']['inventors']['inventor']['inventor-name']['name']['$']
              
              
                if (full['exchange-document'][0]['bibliographic-data']['parties']['inventors']['inventor'].length == 1)
                {
                  inventor_names += full['exchange-document'][0]['bibliographic-data']['parties']['inventors']['inventor'][0]['inventor-name']['name']['$'];
                } else 
                {
                    for (i = 0; i < full['exchange-document'][0]['bibliographic-data']['parties']['inventors']['inventor'].length - 1; i++) 
                    {
                      if(full['exchange-document'][0]['bibliographic-data']['parties']['inventors']['inventor'][i]['@data-format'] == 'epodoc')
                      inventor_names += full['exchange-document'][0]['bibliographic-data']['parties']['inventors']['inventor'][i]['inventor-name']['name']['$'] + ", <br>";
                      
                    }
                    if(full['exchange-document'][0]['bibliographic-data']['parties']['inventors']['inventor'][i]['@data-format'] == 'epodoc')
                    inventor_names += full['exchange-document'][0]['bibliographic-data']['parties']['inventors']['inventor'][i]['inventor-name']['name']['$'];
                  }
                  
                  return inventor_names; 
            }
      
      
      
            if (full['exchange-document']['bibliographic-data'] == undefined){
            return null;
          }
            if (full['exchange-document']['bibliographic-data']['parties']['inventors'] == undefined){
            return null;
          }
          
          if(!(Array.isArray(full['exchange-document']['bibliographic-data']['parties']['inventors']['inventor'])))       
            return full['exchange-document']['bibliographic-data']['parties']['inventors']['inventor']['inventor-name']['name']['$']
          
          
            if (full['exchange-document']['bibliographic-data']['parties']['inventors']['inventor'].length == 1)
            {
              inventor_names += full['exchange-document']['bibliographic-data']['parties']['inventors']['inventor'][0]['inventor-name']['name']['$'];
            } else 
            {
                for (i = 0; i < full['exchange-document']['bibliographic-data']['parties']['inventors']['inventor'].length - 1; i++) 
                {
                  if(full['exchange-document']['bibliographic-data']['parties']['inventors']['inventor'][i]['@data-format'] == 'epodoc')
                  inventor_names += full['exchange-document']['bibliographic-data']['parties']['inventors']['inventor'][i]['inventor-name']['name']['$'] + ", <br>";
                  
                }
                if(full['exchange-document']['bibliographic-data']['parties']['inventors']['inventor'][i]['@data-format'] == 'epodoc')
                inventor_names += full['exchange-document']['bibliographic-data']['parties']['inventors']['inventor'][i]['inventor-name']['name']['$'];
              }
              
              return inventor_names; 
        }

    }).withOption('defaultContent', '-default value-'),
 
    DTColumnBuilder.newColumn('patents').withTitle('Assignees:').renderWith(function(data, type, full) 
    {
        if(search_type == 'USPTO')
        {
            var assignee_names = "";
            if (full == null)
              return null;
      
      
            if (full.assignees.length == 1)
              {
                if(full.assignees[0].assignee_first_name != null)            
                  assignee_names += full.assignees[0].assignee_first_name + "&nbsp" + full.assignees[0].assignee_last_name;
              } else 
              {
              for (i = 0; i < full.assignees.length - 1; i++) 
              {
                if(full.assignees[i].assignee_first_name != null)    
                  assignee_names += full.assignees[i].assignee_first_name + "&nbsp" + full.assignees[i].assignee_last_name;
              }
              if(full.assignees[i].assignee_first_name != null)    
                assignee_names += ", " + full.assignees[i].assignee_first_name + "&nbsp" + full.assignees[i].assignee_last_name;
              }
      
              if (assignee_names == "")
              return null;
      
      
              return assignee_names;
        } else {
            var applicants = []
            if(Array.isArray(full['exchange-document'])){
              if(full['exchange-document'][0]['bibliographic-data']['parties']['applicants'] == undefined)
              return null;
              if(full['exchange-document'][0]['bibliographic-data']['parties']['applicants']['applicant'] == undefined)
              return null;
              if(Array.isArray(full['exchange-document'][0]['bibliographic-data']['parties']['applicants']['applicant']))
              {
                for(i = 0; i < full['exchange-document'][0]['bibliographic-data']['parties']['applicants']['applicant'].length; i++){       
                  if(full['exchange-document'][0]['bibliographic-data']['parties']['applicants']['applicant'][i]['@data-format'] == 'epodoc')
                  applicants.push(full['exchange-document'][0]['bibliographic-data']['parties']['applicants']['applicant'][i]['applicant-name']['name']['$'])
                }
                return applicants.toString()
              }
              return full['exchange-document'][0]['bibliographic-data']['parties']['applicants']['applicant']['applicant-name']['$']
              }

              if(full['exchange-document']['bibliographic-data']['parties']['applicants'] == undefined)
              return null;
              if(full['exchange-document']['bibliographic-data']['parties']['applicants']['applicant'] == undefined)
              return null;
   
              if(Array.isArray(full['exchange-document']['bibliographic-data']['parties']['applicants']['applicant']))
              {
                for(i = 0; i < full['exchange-document']['bibliographic-data']['parties']['applicants']['applicant'].length; i++){
                 if(full['exchange-document']['bibliographic-data']['parties']['applicants']['applicant'][i]['@data-format'] == "epodoc")
                  
                  applicants.push(full['exchange-document']['bibliographic-data']['parties']['applicants']['applicant'][i]['applicant-name']['name']['$'])
                }
                return applicants.toString()
              } 
      
            return null
        }

  
     }).withOption('defaultContent', '-default value-').withClass('none'),
     DTColumnBuilder.newColumn('patents').withTitle('Organizations:').renderWith(function(data, type, full) 
    {
     var organization_names = "";
 
     if(search_type == 'USPTO'){
        if (full == null)
        return null;
          
          if (full.assignees.length == 1)
          {
            if(full.assignees[0].assignee_organization != null) 
            organization_names = full.assignees[0].assignee_organization;
          } else 
          {
            for (i = 0; i < full.assignees.length - 1; i++) 
            {
              if(full.assignees[i].assignee_organization != null) 
              organization_names += full.assignees[i].assignee_organization ;
            }
            if(full.assignees[i].assignee_organization != null)
            organization_names +=  ", " + full.assignees[i].assignee_organization;
          }
          if (organization_names == "")
          return null;
          
          return organization_names;  
     } else {
         return null
     }

      
     }).withOption('defaultContent', '-default value-').withClass('none'),
     
     DTColumnBuilder.newColumn('patents').withTitle('View Document').renderWith(function(data, type, full) 
     {
        if(search_type == 'USPTO'){
            if (full== null)
            return null;
      
            var patent_url_text = "http://patft.uspto.gov/netacgi/nph-Parser?Sect1=PTO1&Sect2=HITOFF&d=PALL&p=1&u=%2Fnetahtml%2FPTO%2Fsrchnum.htm&r=1&f=G&l=50&s1=";
            patent_url_text += full.patent_number + ".PN.&OS=PN/" + full.patent_number + "&RS=PN/" + full.patent_number;
            var link = '<a href="' + patent_url_text + '" target="_blank">Full Text</a>';
             return link; 
        } else {
            return null
        }
              
     }).withOption('defaultContent', '-default value-').notSortable(),
 
     DTColumnBuilder.newColumn('patents').withTitle('Cited patents:').renderWith(function(data, type, full) 
     {
       
        if(search_type == 'USPTO'){
            if (full== null)
            return null;
            var cited_patetns_titles = "";
            var patent_url_text = "http://patft.uspto.gov/netacgi/nph-Parser?Sect1=PTO1&Sect2=HITOFF&d=PALL&p=1&u=%2Fnetahtml%2FPTO%2Fsrchnum.htm&r=1&f=G&l=50&s1=";
            
      
            if (full.cited_patents.length == 1)
            {
              if(full.cited_patents[0].cited_patent_title != null){        
              patent_url_text += full.cited_patents[0].cited_patent_number + ".PN.&OS=PN/" + full.cited_patents[0].cited_patent_number + "&RS=PN/" + full.cited_patents[0].cited_patent_number;
              cited_patetns_titles = '<br><a href="' + patent_url_text + '" target="_blank">'+full.cited_patents[0].cited_patent_title +'</a>';}
      
            } else 
            {
              
              for (i = 0; i < full.cited_patents.length - 1; i++) 
              {
                if(full.cited_patents[i].cited_patent_title != null){ 
                  patent_url_text = "http://patft.uspto.gov/netacgi/nph-Parser?Sect1=PTO1&Sect2=HITOFF&d=PALL&p=1&u=%2Fnetahtml%2FPTO%2Fsrchnum.htm&r=1&f=G&l=50&s1=";
                  patent_url_text += full.cited_patents[i].cited_patent_number + ".PN.&OS=PN/" + full.cited_patents[i].cited_patent_number + "&RS=PN/" + full.cited_patents[i].cited_patent_number;
                  cited_patetns_titles += '<br><a href="' + patent_url_text + '" target="_blank">'+full.cited_patents[i].cited_patent_title +'</a>';
          
                }
              }
              if(full.cited_patents[i].cited_patent_title != null){
                patent_url_text = "http://patft.uspto.gov/netacgi/nph-Parser?Sect1=PTO1&Sect2=HITOFF&d=PALL&p=1&u=%2Fnetahtml%2FPTO%2Fsrchnum.htm&r=1&f=G&l=50&s1=";
                patent_url_text += full.cited_patents[i].cited_patent_number + ".PN.&OS=PN/" + full.cited_patents[i].cited_patent_number + "&RS=PN/" + full.cited_patents[i].cited_patent_number;
                cited_patetns_titles += '<br><a href="' + patent_url_text + '" target="_blank">'+full.cited_patents[i].cited_patent_title +'</a>';
        }
            }
            if (cited_patetns_titles == "")
            return null;
            
            return cited_patetns_titles;     
        } else {
            return null
        }
    }).withOption('defaultContent', '-default value-').withClass('none')     
   ]; 
  vm.search = search;
  vm.clear = clear;
  vm.dtInstance = {};            
  vm.dtOptions = uspto_dtOptions;
  vm.dtColumns = uspto_dtColumns;

function ServerData(sSource, aoData, fnCallback, oSettings) {  

  if(search_type== "USPTO"){
    oSettings.jqXHR = $.ajax({
      'dataType': 'json',
      'type': 'get',
      'url': patentFunctions.getUsptoUrl(vm.query, vm.date_begin,vm.date_end, vm.first_name, vm.last_name, vm.organization_name),
      'data': aoData,
      "success": function(json){
          if (!json.patents) {            
            return fnCallback({
              "patents": []
            });
          }          
          fnCallback(json);
      }
  });
  }else {
    if(token == undefined){
      generate_epo_token();
      return;
    }

    oSettings.jqXHR = $.ajax({
      'dataType': 'json',
      'type': 'get',
      headers: {
        'Authorization':'Bearer '+ token,
        'Accept':'application/json'
    },
      'url': patentFunctions.getEpoUrl(vm.query, vm.date_begin,vm.date_end, vm.first_name, vm.last_name, vm.organization_name), 
      "dataSrc": 'ops:world-patent-data.ops:biblio-search.ops:search-result.exchange-documents',
      'data': aoData,
      "success": function(json){
          json['ops:world-patent-data']['ops:biblio-search']['ops:search-result']['patents'] = json['ops:world-patent-data']['ops:biblio-search']['ops:search-result']['exchange-documents'];
          delete json['ops:world-patent-data']['ops:biblio-search']['ops:search-result']['exchange-documents']
          fnCallback(json['ops:world-patent-data']['ops:biblio-search']['ops:search-result']);
      },
      error: function (response) {
      console.log("error")
      console.log(response)
      //valid_token = false;
      //generate_epo_token();             
    }          
    });
  }
}

function generate_epo_token() {
  if(!valid_token){
    $.ajax({
      url: 'https://ops.epo.org/3.2/auth/accesstoken',
      type: 'POST',
      contentType: 'application/x-www-form-urlencoded',
      data: 'grant_type=client_credentials',
      beforeSend: function(xhr) {
        xhr.setRequestHeader("Authorization", "Basic " + patentFunctions.encodedData);
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
      },
      success: function(response) {
        token = response.access_token;
        vm.dtInstance.reloadData();
      }
    });
    valid_token = true;
  }
  //vm.dtInstance.reloadData();    
}

function search(){   
  vm.dtInstance.DataTable.clear();
  search_type = vm.selection;
  if(
    (vm.query == undefined || vm.query.replace(/ +/g, ' ') =='') && 
    (vm.date_begin == undefined) && 
    (vm.date_end == undefined) &&
    (vm.first_name == undefined || vm.first_name.replace(/ +/g, ' ') =='') && 
    (vm.last_name == undefined || vm.last_name.replace(/ +/g, ' ') =='') && 
    (vm.organization_name == undefined || vm.organization_name.replace(/ +/g, ' ') =='')
  
  ){
    return;
  }

vm.dtInstance.reloadData(); 
}

function clear(){
  vm.date_begin = undefined;
  vm.date_end = undefined;
  vm.first_name = undefined;
  vm.last_name = undefined;
  vm.organization_name = undefined;
}

}
})();




