/*******************************************************************************<?php/*
 *
 * LEIDEN OPEN VARIATION DATABASE (LOVD)
 *
 * Created     : 2007-06-18
 * Modified    : 2009-09-03
 * Version     : 0.5
 * For LOVD    : 2.0-21
 *
 * Copyright   : 2004-2009 Leiden University Medical Center; http://www.LUMC.nl/
 * Programmer  : Ing. Ivo F.A.C. Fokkema <I.F.A.C.Fokkema@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
 *
 *************/

class mutalyzer {
    function getInfo ()
    {
        return
             array(
                    'name' => 'LOVD Mutalyzer connection module',
                    'version' => '0.5',
                    'description' => 'LOVD module to connect to Mutalyzer to verify submitted variants with a reference sequence.',
                    'settings' =>
                             array(
                                    'url' => 'http://eu.liacs.nl/mutalyzer/1.0.4/',
                                    'url_version' => '1.0.4',
                                    'accessionid' => array(),
                                  ),
                  );
    }



    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 FROM ' . TABLE_DBS . ' WHERE genbank = 1');
        while ($r = mysql_fetch_row($qGenes)) {
            // Send GenBank file.
            list($sSymbol, $sFile) = $r;
            if (empty($aSett['accessionid'][$sSymbol])) {
                // 2009-04-22; 2.0-18; Use the known database URL, if possible.
                if (!empty($_CONF['location_url'])) {
                    $sURL = $_CONF['location_url'] . 'genbank/' . $sFile;
                } else {
                    $sURL = PROTOCOL . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) . '/' . ROOT_PATH . 'genbank/' . $sFile;
                }
                $sReply = file_get_contents($aSett['url'] . 'digitalBackdoor.php?method=gbupload&url=' . rawurlencode($sURL));
                if ($sReply && preg_match('/^UD_[a-z0-9_]+$/i', $sReply)) {
                    // Store in settings.
                    // ... UD_NM_004010_40758 UD_DMD_45204
                    $aSett['accessionid'][$sSymbol] = $sReply;
                }
            }
        }
        $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.
            // FIXME; if genbank file (option 1), we need to submit that somehow...
            if (($_CURRDB['genbank'] == 1 && !empty($aSett['accessionid'][$_CURRDB['symbol']])) || ($_CURRDB['genbank'] == 2 && $_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; add lovd_showSID again if value is posted to our pages.
                        // FIXME; we should somehow parse this output.
                        // 2009-04-22; 2.0-18; Add Gene Symbol in URL to support GenBank files containing more than one gene.
                        $aReturn[] = array('', 'print', '<BUTTON type="button" onclick="javascript:if (document.forms[0][\'Variant/DNA\'].value.length > 0) { lovd_openWindow(\'' . $aSett['url'] . 'digitalBackdoor.php?method=namecheck&format=human&mutationname=' . ($_CURRDB['genbank'] == 1? $aSett['accessionid'][$_CURRDB['symbol']] : $_CURRDB['genbank_uri']) . rawurlencode('(' . $_CURRDB['symbol_short'] . '):') . '\' + 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.
        if ($sVersionOld <= '0.4') {
            $aInfo = $this->getInfo();
            $aSett = $GLOBALS['_MODULES']->setSettings('mutalyzer', 'url', $aInfo['settings']['url']);
            $aSett = $GLOBALS['_MODULES']->setSettings('mutalyzer', 'url_version', $aInfo['settings']['url_version']);
        }
    }
}