/*******************************************************************************<?php/*
 *
 * LEIDEN OPEN VARIATION DATABASE (LOVD)
 *
 * Created     : 2007-06-18
 * Modified    : 2011-02-16
 * Version     : 1.0
 * For LOVD    : 2.0-30b
 *
 * Copyright   : 2004-2011 Leiden University Medical Center; http://www.LUMC.nl/
 * Programmers : Ing. Ivo F.A.C. Fokkema <I.F.A.C.Fokkema@LUMC.nl>
 *               Ir. Gerard C.P. Schaafsma <G.C.P.Schaafsma@LUMC.nl>
 * Last edited : Ing. Ivo F.A.C. Fokkema <I.F.A.C.Fokkema@LUMC.nl>
 *
 *
 * This file is part of LOVD.
 *
 * LOVD is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * LOVD is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with LOVD; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 *************/

// 2011-02-03; 2.0-30; Included LOVD 3.0 REST2SOAP module to talk to Mutalyzer's SOAP services.
require ROOT_PATH . 'modules/mutalyzer/REST2SOAP.php';

class mutalyzer {
    function getInfo ()
    {
        return
             array(
                    'name' => 'LOVD Mutalyzer connection module',
                    'version' => '1.0',
                    'description' => 'LOVD module to connect to Mutalyzer to verify submitted variants with a reference sequence.',
                    'settings' =>
                             array(
                                    // 2010-08-23; 2.0-29; changed to Mutalyzer 2.0
                                    'url' => 'http://www.mutalyzer.nl/2.0/',
                                    'url_version' => '2.0',
                                    'accessionid' => array(),
                                  ),
                  );
    }



    function getUDfromMutalyzer ($sData)
    {
        // Fetches the UD number after uploading a GenBank file to Mutalyzer (2.0)
        $aSett = $GLOBALS['_MODULES']->getSettings('mutalyzer');
        $sMutUrl = $aSett['url'] . 'upload';
        // Get data from Mutalyzer
        $aFile = lovd_php_file($sMutUrl, false, $sData);
        foreach ($aFile as $key => $value) {
            if (preg_match('/([A-Z]+_?\d+(\.\d+)?)/', $value, $aMatches)) {
                $sUD = $aMatches[1];
                return $sUD;
            }
        }
        return false;
    }



    function getTranscriptVersionFromMutalyzer ($sRefSeqGenomic, $sRefSeqTranscript)
    {
        // 2010-12-09; 2.0-30; Fetches Mutalyzer transcript version (e.g. DMD_v001)
        $_MutalyzerWS = new REST2SOAP();
        $_MutalyzerWS->sSoapURL = 'http://www.mutalyzer.nl/2.0/services';
        if (substr($sRefSeqGenomic, 0, 3) == 'NG_' && substr($sRefSeqTranscript, 0, 3) == 'NM_') {
            $aFile = $_MutalyzerWS->moduleCall('getGeneAndTranscript', array('genomicReference' => $sRefSeqGenomic, 'transcriptReference' => $sRefSeqTranscript));
        }
        if (!empty($aFile) && is_array($aFile) && $aFile[0] != 'SOAP-ENV:Server') {
            return $aFile[0];
        }
    }



    function enable ()
    {
        // Will be run when module is getting enabled.
        $aSett = $GLOBALS['_MODULES']->getSettings('mutalyzer');

        // Per gene, check if there is a genbank file that we can send to mutalyzer.
        // If so, send it and retrieve accessionnumber. This needs to be stored and used as a reference.
        $qGenes = mysql_query('SELECT symbol, genbank_uri, refseq_genomic, refseq_mrna FROM ' . TABLE_DBS . ' WHERE genbank = 1');
        while ($r = mysql_fetch_row($qGenes)) {
            // Send GenBank file.
            list($sSymbol, $sFile, $sRefSeqGenomic, $sRefSeqTranscript) = $r;
            if (empty($aSett['accessionid'][$sSymbol])) {
                $sData = 'invoermethode=file&bestandsveld=' . urlencode(file_get_contents(ROOT_PATH . 'genbank/' . $sFile));
                $sUD = $this->getUDfromMutalyzer($sData);
                if ($sUD) {
                    $aSett['accessionid'][$sSymbol]['UD'] = $sUD; // 2010-12-09; 2.0-30; Added index UD
                    // 2010-12-09; 2.0-30; add Mutalyzer transcript version to $aSett('accessionid']
                    $sMutVersion = $this->getTranscriptVersionFromMutalyzer($sRefSeqGenomic, $sRefSeqTranscript);
                    if ($sMutVersion) {
                        $aSett['accessionid'][$sSymbol]['MutVer'] = $sMutVersion;
                    }
                }
            }
        }
        $GLOBALS['_MODULES']->setSettings('mutalyzer', $aSett);
    }



    function processForm ($sForm, & $aForm)
    {
        // Process LOVD form data before it gets to the screen.

        if (in_array($sForm, array('SubmitVariantData', 'SubmitVariantsEdit'))) {
            $aSett = $GLOBALS['_MODULES']->getSettings('mutalyzer');
            $_CURRDB = mysql_fetch_assoc(mysql_query('SELECT * FROM ' . TABLE_DBS . ' WHERE symbol = "' . ($sForm == 'SubmitVariantData'? $_POST['gene'] : $_SESSION['currdb']) . '"'));
            $_CURRDB['symbol_short'] = substr($_CURRDB['symbol'], 0, strpos($_CURRDB['symbol'] . '_', '_'));

            // We only work, if we've got a reference sequence in the database.
            if (($_CURRDB['genbank'] == 1 && !empty($aSett['accessionid'][$_CURRDB['symbol']]) && !empty($_CURRDB['refseq_mrna'])) || ($_CURRDB['genbank'] > 1 && $_CURRDB['genbank_uri'])) {
                $aReturn = array();
                foreach ($aForm as $nItem => $aItem) {
                    // Line by line, go through the form.
                    if ($aItem[2] == 'Variant/DNA') {
                        // Add mutalyzer button.
                        $aReturn[] = $aItem;
                        // FIXME; we should somehow parse this output.
                        // 2011-02-16; 2.0-30b; Fixed bug when calling mutationName, the UD must now be retrieved from an array.
                        // (Ivo) There are actually more problems with this script. Implementing a quick fix: try different ways to link to Mutalyzer.
                        $sURL = '';
                        if (!empty($aSett['accessionid'][$_CURRDB['symbol']]['MutVer'])) {
                            $sURL = 'check?mutationName=';
                            if ($aSett['accessionid'][$_CURRDB['symbol']]['UD']) {
                                // FIXME; MutVer has not been calculated using this file, so I'm not sure this is a good idea...
                                $sURL .= $aSett['accessionid'][$_CURRDB['symbol']]['UD'];
                            } else {
                                $sURL .= $_CURRDB['refseq_genomic'];
                            }
                            $sURL .= rawurlencode('(' . $aSett['accessionid'][$_CURRDB['symbol']]['MutVer'] . '):');
                        } else {
                            $sURL = 'getGS?variantRecord=' . $_CURRDB['refseq_mrna'] . '&forward=1&mutationName=' . ($_CURRDB['genbank'] == 1? $aSett['accessionid'][$_CURRDB['symbol']]['UD'] : $_CURRDB['genbank_uri']) . rawurlencode(':');
                        }
                        $aReturn[] = array('', 'print', '<BUTTON type="button" onclick="javascript:if (document.forms[0][\'Variant/DNA\'].value.length > 0) { lovd_openWindow(\'' . $aSett['url'] . $sURL . '\' + encodeURIComponent(document.forms[0][\'Variant/DNA\'].value), \'ModuleMutalyzerNamecheck\', 800, 400); } else { window.alert(\'Please fill in the DNA field.\'); } return false;">Check variant with Mutalyzer ' . $aSett['url_version'] . '</BUTTON>');
                    } else {
                        $aReturn[] = $aItem;
                    }
                }
                $aForm = $aReturn;
                return true;
            }
        }
        return false;
    }





    function upgrade ($sVersionOld)
    {
        // Run necessary code for upgrading this module.
        $aInfo = $this->getInfo();

        // Module version 0.8 has switched to Mutalyzer 2.0.
        if ($sVersionOld <= '0.7') {
            $GLOBALS['_MODULES']->setSettings('mutalyzer', 'url', $aInfo['settings']['url']);
            $GLOBALS['_MODULES']->setSettings('mutalyzer', 'url_version', $aInfo['settings']['url_version']);
            // Get the settings from TABLE_MODULES
            $aSett = $GLOBALS['_MODULES']->getSettings('mutalyzer');

            // Now see which genes have uploaded their own GenBank file
            $qGenes = mysql_query('SELECT symbol, genbank_uri, refseq_genomic, refseq_mrna FROM ' . TABLE_DBS . ' WHERE genbank = 1');
            // Now for each gene, get a Mutalyzer 2 UD_ number
            while ($r = mysql_fetch_row($qGenes)) {
                // Send GenBank file.
                list($sSymbol, $sFile, $sRefSeqGenomic, $sRefSeqTranscript) = $r;
                $sData = 'invoermethode=file&bestandsveld=' . urlencode(file_get_contents(ROOT_PATH . 'genbank/' . $sFile));
                $sUD = $this->getUDfromMutalyzer($sData);
                if ($sUD) {
                    // Store in settings: UD_012345678901
                    $aSett['accessionid'][$sSymbol] = array('UD' => $sUD);// 2010-12-09; 2.0-30; Added index UD
                    // 2010-12-09; 2.0-30; add Mutalyzer transcript version to $aSett('accessionid']
                    $sMutVersion = $this->getTranscriptVersionFromMutalyzer($sRefSeqGenomic, $sRefSeqTranscript);
                    if ($sMutVersion) {
                        $aSett['accessionid'][$sSymbol]['MutVer'] = $sMutVersion;
                    }
                }
            }
    
            // Now see which genes use a Mutalyzer (1.0.4) UD identifier
            $qGenes = mysql_query('SELECT symbol, genbank_uri, refseq_genomic, refseq_mrna FROM ' . TABLE_DBS . ' WHERE genbank = 3');
            while ($r = mysql_fetch_row($qGenes)) {
                // Send GenBank file.
                list($sSymbol, $sFile, $sRefSeqGenomic, $sRefSeqTranscript) = $r;
                // 2011-01-19; 2.0-30; directory in url of mutalyzer 1.0.4 changed
                $sData = 'invoermethode=url&urlveld=http://localhost/1.0.4_old/custom/' . urlencode($sFile); // localhost on Mutalyzer server!
                $sUD = $this->getUDfromMutalyzer($sData);
                if ($sUD) {
                    // Store in settings: UD_012345678901
                    // 2011-01-19; 2.0-30; changed $aSett['accessionid'][$sSymbol] from string to array to store both the UD and the mutalyzer transcript version (e.g. v001)
                    $aSett['accessionid'][$sSymbol] = array('UD' => $sUD);
                    // update TABLE_DBS
                    $sQ = 'UPDATE ' . TABLE_DBS . ' SET genbank_uri="' . $aSett['accessionid'][$sSymbol]['UD'] . '" WHERE symbol="' . $sSymbol . '"';
                    $q = mysql_query($sQ);
                    // 2010-12-09; 2.0-30; add Mutalyzer transcript version to $aSett('accessionid']
                    $sMutVersion = $this->getTranscriptVersionFromMutalyzer($sRefSeqGenomic, $sRefSeqTranscript);
                    if ($sMutVersion) {
                        $aSett['accessionid'][$sSymbol]['MutVer'] = $sMutVersion;
                    }
                }
            }


        } elseif ($sVersionOld == '0.8') {
            // Get the settings from TABLE_MODULES
            $aSett = $GLOBALS['_MODULES']->getSettings('mutalyzer');

            // 2011-01-14; 2.0-30; structure of $aSett['accessionid'][$sSymbol] changed from string to array
            foreach ($aSett['accessionid'] as $sSymbol => $sUD) {
                $aSett['accessionid'][$sSymbol] = array('UD' => $sUD);
                //add Mutalyzer transcript version to $aSett('accessionid'][$sSymbol]
                $sQ = 'SELECT refseq_genomic, refseq_mrna FROM ' . TABLE_DBS . ' WHERE symbol="' . $sSymbol . '"';
                $q = mysql_query($sQ);
                while ($r = mysql_fetch_row($q)) {
                    list($sRefSeqGenomic, $sRefSeqTranscript) = $r;
                    $sMutVersion = $this->getTranscriptVersionFromMutalyzer($sRefSeqGenomic, $sRefSeqTranscript);
                    if ($sMutVersion) {
                        $aSett['accessionid'][$sSymbol]['MutVer'] = $sMutVersion;
                    }
                }
            }
        }
        // now also set the new settings
        if (!empty($aSett)) {
            $GLOBALS['_MODULES']->setSettings('mutalyzer', $aSett);
        }
    }

}
