/* variome.c was originally generated by the autoSql program, which also 
 * generated variome.h and variome.sql.  This module links the database and
 * the RAM representation of objects. */

/* Copyright (C) 2014 The Regents of the University of California 
 * See kent/LICENSE or http://genome.ucsc.edu/license/ for licensing information. */

#include "common.h"
#include "linefile.h"
#include "dystring.h"
#include "jksql.h"
#include "variome.h"
#include "hdb.h"
#include "binRange.h"


void variomeStaticLoad(char **row, struct variome *ret)
/* Load a row from variome table into ret.  The contents of ret will
 * be replaced at the next call to this function. */
{

ret->bin = sqlUnsigned(row[0]);
ret->chrom = row[1];
ret->chromStart = sqlUnsigned(row[2]);
ret->chromEnd = sqlUnsigned(row[3]);
ret->name = row[4];
ret->score = sqlUnsigned(row[5]);
safecpy(ret->strand, sizeof(ret->strand), row[6]);
ret->db = row[7];
ret->owner = row[8];
ret->color = row[9];
ret->class = row[10];
ret->creationDate = row[11];
ret->lastModifiedDate = row[12];
ret->descriptionKey = row[13];
ret->id = sqlUnsigned(row[14]);
ret->geneSymbol = row[15];
}

struct variome *variomeLoad(char **row)
/* Load a variome from row fetched with select * from variome
 * from database.  Dispose of this with variomeFree(). */
{
struct variome *ret;

AllocVar(ret);
ret->bin = sqlUnsigned(row[0]);
ret->chrom = cloneString(row[1]);
ret->chromStart = sqlUnsigned(row[2]);
ret->chromEnd = sqlUnsigned(row[3]);
ret->name = cloneString(row[4]);
ret->score = sqlUnsigned(row[5]);
safecpy(ret->strand, sizeof(ret->strand), row[6]);
ret->db = cloneString(row[7]);
ret->owner = cloneString(row[8]);
ret->color = cloneString(row[9]);
ret->class = cloneString(row[10]);
ret->creationDate = cloneString(row[11]);
ret->lastModifiedDate = cloneString(row[12]);
ret->descriptionKey = cloneString(row[13]);
ret->id = sqlUnsigned(row[14]);
ret->geneSymbol = cloneString(row[15]);
return ret;
}

struct variome *variomeLoadAll(char *fileName) 
/* Load all variome from a whitespace-separated file.
 * Dispose of this with variomeFreeList(). */
{
struct variome *list = NULL, *el;
struct lineFile *lf = lineFileOpen(fileName, TRUE);
char *row[16];

while (lineFileRow(lf, row))
    {
    el = variomeLoad(row);
    slAddHead(&list, el);
    }
lineFileClose(&lf);
slReverse(&list);
return list;
}

struct variome *variomeLoadAllByChar(char *fileName, char chopper) 
/* Load all variome from a chopper separated file.
 * Dispose of this with variomeFreeList(). */
{
struct variome *list = NULL, *el;
struct lineFile *lf = lineFileOpen(fileName, TRUE);
char *row[16];

while (lineFileNextCharRow(lf, chopper, row, ArraySize(row)))
    {
    el = variomeLoad(row);
    slAddHead(&list, el);
    }
lineFileClose(&lf);
slReverse(&list);
return list;
}

struct variome *variomeLoadByQuery(struct sqlConnection *conn, char *query)
/* Load all variome from table that satisfy the query given.  
 * Where query is of the form 'select * from example where something=something'
 * or 'select example.* from example, anotherTable where example.something = 
 * anotherTable.something'.
 * Dispose of this with variomeFreeList(). */
{
struct variome *list = NULL, *el;
struct sqlResult *sr;
char **row;

sr = sqlGetResult(conn, query);
while ((row = sqlNextRow(sr)) != NULL)
    {
    el = variomeLoad(row);
    slAddHead(&list, el);
    }
slReverse(&list);
sqlFreeResult(&sr);
return list;
}

void variomeSaveToDb(struct sqlConnection *conn, struct variome *el, char *tableName, int updateSize)
/* Save variome as a row to the table specified by tableName. 
 * As blob fields may be arbitrary size updateSize specifies the approx size
 * of a string that would contain the entire query. Arrays of native types are
 * converted to comma separated strings and loaded as such, User defined types are
 * inserted as NULL. Strings are automatically escaped to allow insertion into the database. */
{
struct dyString *update = dyStringNew(updateSize);
sqlDyStringPrintf(update, "insert into %s values ( %u,'%s',%u,%u,'%s',%u,'%s','%s','%s','%s','%s','%s','%s','%s',%u,'%s')", 
	tableName,  el->bin,  el->chrom,  el->chromStart,  el->chromEnd,  el->name,  el->score,  el->strand,  el->db,  el->owner,  el->color,  el->class,  el->creationDate,  el->lastModifiedDate,  el->descriptionKey,  el->id,  el->geneSymbol);
sqlUpdate(conn, update->string);
dyStringFree(&update);
}


struct variome *variomeCommaIn(char **pS, struct variome *ret)
/* Create a variome out of a comma separated string. 
 * This will fill in ret if non-null, otherwise will
 * return a new variome */
{
char *s = *pS;

if (ret == NULL)
    AllocVar(ret);
ret->bin = sqlUnsignedComma(&s);
ret->chrom = sqlStringComma(&s);
ret->chromStart = sqlUnsignedComma(&s);
ret->chromEnd = sqlUnsignedComma(&s);
ret->name = sqlStringComma(&s);
ret->score = sqlUnsignedComma(&s);
sqlFixedStringComma(&s, ret->strand, sizeof(ret->strand));
ret->db = sqlStringComma(&s);
ret->owner = sqlStringComma(&s);
ret->color = sqlStringComma(&s);
ret->class = sqlStringComma(&s);
ret->creationDate = sqlStringComma(&s);
ret->lastModifiedDate = sqlStringComma(&s);
ret->descriptionKey = sqlStringComma(&s);
ret->id = sqlUnsignedComma(&s);
ret->geneSymbol = sqlStringComma(&s);
*pS = s;
return ret;
}

void variomeFree(struct variome **pEl)
/* Free a single dynamically allocated variome such as created
 * with variomeLoad(). */
{
struct variome *el;

if ((el = *pEl) == NULL) return;
freeMem(el->chrom);
freeMem(el->name);
freeMem(el->db);
freeMem(el->owner);
freeMem(el->color);
freeMem(el->class);
freeMem(el->creationDate);
freeMem(el->lastModifiedDate);
freeMem(el->descriptionKey);
freeMem(el->geneSymbol);
freez(pEl);
}

void variomeFreeList(struct variome **pList)
/* Free a list of dynamically allocated variome's */
{
struct variome *el, *next;

for (el = *pList; el != NULL; el = next)
    {
    next = el->next;
    variomeFree(&el);
    }
*pList = NULL;
}

void variomeOutput(struct variome *el, FILE *f, char sep, char lastSep) 
/* Print out variome.  Separate fields with sep. Follow last field with lastSep. */
{
fprintf(f, "%u", el->bin);
fputc(sep,f);
if (sep == ',') fputc('"',f);
fprintf(f, "%s", el->chrom);
if (sep == ',') fputc('"',f);
fputc(sep,f);
fprintf(f, "%u", el->chromStart);
fputc(sep,f);
fprintf(f, "%u", el->chromEnd);
fputc(sep,f);
if (sep == ',') fputc('"',f);
fprintf(f, "%s", el->name);
if (sep == ',') fputc('"',f);
fputc(sep,f);
fprintf(f, "%u", el->score);
fputc(sep,f);
if (sep == ',') fputc('"',f);
fprintf(f, "%s", el->strand);
if (sep == ',') fputc('"',f);
fputc(sep,f);
if (sep == ',') fputc('"',f);
fprintf(f, "%s", el->db);
if (sep == ',') fputc('"',f);
fputc(sep,f);
if (sep == ',') fputc('"',f);
fprintf(f, "%s", el->owner);
if (sep == ',') fputc('"',f);
fputc(sep,f);
if (sep == ',') fputc('"',f);
fprintf(f, "%s", el->color);
if (sep == ',') fputc('"',f);
fputc(sep,f);
if (sep == ',') fputc('"',f);
fprintf(f, "%s", el->class);
if (sep == ',') fputc('"',f);
fputc(sep,f);
if (sep == ',') fputc('"',f);
fprintf(f, "%s", el->creationDate);
if (sep == ',') fputc('"',f);
fputc(sep,f);
if (sep == ',') fputc('"',f);
fprintf(f, "%s", el->lastModifiedDate);
if (sep == ',') fputc('"',f);
fputc(sep,f);
if (sep == ',') fputc('"',f);
fprintf(f, "%s", el->descriptionKey);
if (sep == ',') fputc('"',f);
fputc(sep,f);
fprintf(f, "%u", el->id);
fputc(sep,f);
if (sep == ',') fputc('"',f);
fprintf(f, "%s", el->geneSymbol);
if (sep == ',') fputc('"',f);
fputc(lastSep,f);
}

/* -------------------------------- End autoSql Generated Code -------------------------------- */
#include "wikiTrack.h"
#include "wikiLink.h"
#include "web.h"
#include "cheapcgi.h"
#include "hPrint.h"
#include "hgConfig.h"
#include "hCommon.h"

char *variomeClassList[] = {
    "substitution",
    "insertion",
    "duplication",
    "deletion",
    "inversion",
    "complex",
    ITEM_NOT_CLASSIFIED,
};

char *variomeCoorList[] = {
    "exact coordinates",
    "estimated coordinates",
};

int variomeClassCnt = ArraySize(variomeClassList);

struct variome *findVariomeItemId(char *db, char *wikiItemId)
/* given a wikiItemId return the row from the table */
{
struct variome *item;
char query[256];
struct sqlConnection *conn = wikiConnect();

sqlSafef(query, ArraySize(query), "SELECT * FROM variome WHERE id='%s' limit 1",
        wikiItemId);

item = variomeLoadByQuery(conn, query);
if (NULL == item)
    errAbort("display wiki item: failed to load item '%s'", wikiItemId);

wikiDisconnect(&conn);
return item;
}

/* use functions from lib/wikiTrack.c, lib/wikiLink.c for accessing wiki pages */

int addVariomeItem(char *db, char *chrom, int start, int end,
    char *name, int score, char *strand, char *owner, char *class,
        char *color, char *category, char *geneSymbol, char *wikiKey)
/* create new Variome row with given parameters */
{
struct sqlConnection *conn = wikiConnect();
struct variome *newItem;
AllocVar(newItem);
newItem->bin = binFromRange(start, end);
newItem->chrom = cloneString(chrom);
newItem->chromStart = start;
newItem->chromEnd = end;
newItem->name = cloneString(name);
newItem->score = score;
if (sameString(strand, "plus"))
    safef(newItem->strand, sizeof(newItem->strand), "%s", "+");
else if (sameString(strand, "minus"))
    safef(newItem->strand, sizeof(newItem->strand), "%s", "-");
else 
    safef(newItem->strand, sizeof(newItem->strand), "%s", " ");
newItem->db = cloneString(db);
newItem->owner = cloneString(owner);
newItem->class = cloneString(class);
newItem->color = cloneString(color);
newItem->creationDate = cloneString("0");
newItem->lastModifiedDate = cloneString("0");
newItem->descriptionKey = cloneString("0");
newItem->id = 0;
newItem->geneSymbol = cloneString(geneSymbol);

variomeSaveToDb(conn, newItem, "variome", 1024);

int id = sqlLastAutoId(conn);
char descriptionKey[256];
/* when wikiKey is NULL, assign the default key of category:db-id,
 *      else, it is the proper key
 */
if (wikiKey)
    safef(descriptionKey,ArraySize(descriptionKey), "%s", wikiKey);
else
    safef(descriptionKey,ArraySize(descriptionKey),
        "%s:%s-%d", category, db, id);

variomeFree(&newItem);

char query[1024];
sqlSafef(query, ArraySize(query), "UPDATE %s set creationDate=now(),lastModifiedDate=now(),descriptionKey='%s' WHERE id='%d'",
    "variome", descriptionKey, id);

sqlUpdate(conn,query);
wikiDisconnect(&conn);
return (id);
}

void updateVariomeLastModifiedDate(char *db, int id)
/* set lastModifiedDate to now() */
{
char query[512];
struct sqlConnection *conn = wikiConnect();

sqlSafef(query, ArraySize(query),
    "UPDATE %s set lastModifiedDate=now() WHERE id='%d'",
        "variome", id);
sqlUpdate(conn,query);
wikiDisconnect(&conn);
}

void deleteVariomeItem(char *db, int id)
/* delete the item with specified id */
{
char query[512];
struct sqlConnection *conn = wikiConnect();
sqlSafef(query, ArraySize(query), "DELETE FROM %s WHERE id='%d'",
        "variome", id);
sqlUpdate(conn,query);
wikiDisconnect(&conn);
}

/* prefixComments and addDescription used from wikiTrack.c */

