#!/usr/local/icmchemist/icmchemist64 -w/usr/local/icmchemist

# content type
printf "Content-type: text/html;\n\n"

# get CGI params (GET or POST)
params = Collection(web) 

act = Exist(params,"act") ? params,["act"] : ""

if (act == "") then
#
# Generates HTML page with the editor and placeholder for the search results
#
"""
  <!DOCTYPE HTML>
  <html>
  <head>
  <meta http-equiv="X-UA-Compatible" content="IE=edge" >
  <title>Molsoft Chemical Search Demo</title>
  <link rel="stylesheet" type="text/css" href="chemsearch.css">

  <script src="http://www.molsoft.com/web/moledit.js" type="text/javascript"></script>
  <script>
  var fromIdHistory = [];
  function next(fromid)
  {
    if (document.moledit.isEmpty())
      return;
    fromIdHistory[fromIdHistory.length] = fromid;
    runSearch(fromid);
  }
  function prev()
  {
     if (document.moledit.isEmpty())
       return;
     if (fromIdHistory.length > 1) {
       var id =  fromIdHistory[fromIdHistory.length-2];
       fromIdHistory.splice(fromIdHistory.length-1,1);
       runSearch(id);
     }
  }

  function runSearch(fromid)
  {
    document.moledit.chem.toSmiles( function (smi) {
      var req = getXMLObject(true); 
      var that = this;
      var e = document.getElementById("searchResult");
      var maxhits = parseInt( document.getElementById("hitsPerPage").value );
      e.innerHTML = '<br><br><img src="ajax-loader.gif" >'
      req.onload = function (e) {
        //
        // search results are ready here
        //
        var res = req.responseText.split("\n");
        var n = parseInt(res[0]); // number of hits

        var e = document.getElementById("searchResult");  
        if (n == 0) {
           e.innerHTML = "no hits"
        } else {
           var lastId = parseInt(res[3]);

           var s_prevLink = ( fromIdHistory.length > 1 ) ? sprintf('<a href="javascript:prev()">&lt;&lt;</a>') : ""
           var s_nextLink = ( n == maxhits             ) ? sprintf('<a href="javascript:next(%d)">&gt;&gt;</a>',lastId+1) : "";

           var s_html = sprintf('<p>%s %d hits %s</p>', s_prevLink ,n, s_nextLink );
           s_html += '<div style="width: 90%; height: 800px; overflow-y: scroll;">' + res[1] + '</div>'
           e.innerHTML = s_html; // table with hits
           eval( res[2] ); // evaluate javascript code to draw chemical structures
        }
      }
      // send search request
      var url =  sprintf("chemsearch.cgi?act=search&smi=%s&type=%s&fromid=%d&maxhits=%d", 
         encodeURIComponent(smi), document.getElementById('searchType').value, fromid, maxhits  );
      console.log(url);
      req.open("GET", url );
      req.send();
    },
    false );
  }
  </script>
  </head>
  <body>
  <center>
  <h1> Molsoft Chemical Search Demo </h1>
  <p>
  Draw the structure and click the search button: <button onClick="fromIdHistory=[];next(1);">Search</button> by:
  <select id="searchType"> 
     <option value="sstructure">Substructure</option> 
     <option value="similarity">Similarity</option>
     <option value="exact">Exact</option> 
  </select>
  Hits per page:
  <select id="hitsPerPage"> <option>10</option> <option>50</option> <option>100</option> </select>
  <p>
  <div id="chem1" style="width:590px;border:2px solid gray; border-radius:5px;"></div>
  <script>document.moledit = new ChemicalView("", 'chem1', 500, 400 );</script>
  <p>Click <a href="chemsearch.cgi?act=source" target="_blank">here</a> to see the source code. 
  Check <a href="http://molsoft.com/icm/cgi-programming-with-icm.html" target="_blank">ICM scripting manual</a> for more information</p>
  
  <div id="searchResult"> </div>

  </center>
  </body>
  </html>
"""

elseif (act == "search" & Exist(params,"smi") ) then
#
# perform chemical search return the results 
# line 1: number of hits
# line 2: HTML table with result
# line 3: javascript code to render compounds
    connect molcart filename="PDBligands_2D.molt"

    searchType = Exist(params,"type")    ? params["type"]   : "sstructure"
    fromid     = Exist(params,"fromid")  ? Integer(params["fromid"])   : 1
    maxhits    = Exist(params,"maxhits") ? Integer(params["maxhits"])  : 10

    find molcart $searchType params["smi"] table="PDBligands_2D" name="t" number=maxhits query = " t.molid >= " + fromid 
    
    show Nof(t)
    if (Nof(t) > 0) then
      add column t Predict(t.mol)
      show html t output = "s_html"
      show Replace(Match(s_html,"<body.*?>(?n)(.*)</body>", 1 ), "\n" " ")
      show Replace(Match(s_html,"<script.?>(?n)(.*)</script>", 1 ) + ";onLoad_t();",  "\n" " ")
      show t.molid[$]
    endif
elseif (act == "source" ) then
  read string "chemsearch.cgi" 
  show "<pre><code>" + Replace(s_out,{"<",">","&"},{"&lt;","&gt;","&amp;"}) + "</code></pre>"
endif

quit