# Path: tkp/db/alchemy/image.py
# def insert_dataset(session, description):
#     rerun = session.query(func.max(Dataset.rerun)). \
#         select_from(Dataset).  \
#         filter(Dataset.description == "description"). \
#         one()[0]
# 
#     if not rerun:
#         rerun = 0
#     else:
#         rerun += 1
# 
#     dataset = Dataset(rerun=rerun,
#                       process_start_ts=datetime.now(),
#                       description=description)
#     session.add(dataset)
#     return dataset
# 
# Path: tkp/db/generic.py
# def columns_from_table(table, keywords=None, alias=None, where=None,
#                        order=None):
#     """Obtain specific column (keywords) values from 'table', with
#     kwargs limitations.
# 
#     A very simple helper function, that builds an SQL query to obtain
#     the specified columns from 'table', and then executes that
#     query. Optionally, the WHERE clause can be specified using the
#     where dictionary. It returns a list of a
#     dict (with the originally supplied keywords as dictionary keys),
#     which can be empty.
# 
#     Example:
# 
#         >>> columns_from_table('image', \
#             keywords=['taustart_ts', 'tau_time', 'freq_eff', 'freq_bw'], where={'imageid': 1})
#             [{'freq_eff': 133984375.0, 'taustart_ts': datetime.datetime(2010, 10, 9, 9, 4, 2), 'tau_time': 14400.0, 'freq_bw': 1953125.0}]
# 
#         This builds the SQL query:
#         "SELECT taustart_ts, tau_time, freq_eff, freq_bw FROM image WHERE imageid=1"
# 
#     This function is implemented mainly to abstract and hide the SQL
#     functionality from the Python interface.
# 
#     Args:
# 
#         conn: database connection object
# 
#         table (string): database table name
# 
#     Kwargs:
# 
#         keywords (uple): column names to select from the table. None indicates all ('*')
# 
#         where (dict): where clause for the query, specified as a set
#             of 'key = value' comparisons. Comparisons are and-ed
#             together. Obviously, only 'is equal' comparisons are
#             possible.
# 
#         alias (dict): Chosen aliases for the column names,
#                     used when constructing the returned list of dictionaries
#                     
#         order (string): ORDER BY key.
# 
#     Returns:
# 
#         (tuple): list of dicts. Each dict contains the given keywords,
#             or all if keywords=None. Each element of the list
#             corresponds to a table row.
# 
#     """
#     if keywords is None:
#         query = "SELECT * FROM " + table
#     else:
#         query = "SELECT " + ", ".join(keywords) + " FROM " + table
#     if where is None:
#         where = {}
#     where_args = tuple(where.itervalues())
#     where = " AND ".join(["%s=%%s" % key for key in where.iterkeys()])
#     if where:
#         query += " WHERE " + where
#     if order:
#         query += " ORDER BY " + order
# 
#     cursor = tkp.db.execute(query, where_args)
#     results = cursor.fetchall()
#     results_dict = convert_db_rows_to_dicts(results, alias_map=alias)
#     return results_dict
# 
# Path: tkp/utility/coordinates.py
# def alpha_inflate(theta, decl):
#     """Compute the ra expansion for a given theta at a given declination
#     
#     Keyword arguments:
#     theta, decl are both in decimal degrees.
#     
#     Return value:
#     alpha -- RA inflation in decimal degrees
# 
#     For a derivation, see MSR TR 2006 52, Section 2.1
#     http://research.microsoft.com/apps/pubs/default.aspx?id=64524
# 
#     """
#     if abs(decl) + theta > 89.9:
#         return 180.0
#     else:
#         return math.degrees(abs(math.atan(math.sin(math.radians(theta)) / math.sqrt(abs(math.cos(math.radians(decl - theta)) * math.cos(math.radians(decl + theta)))))))
# 
# Path: tkp/utility/coordinates.py
# def eq_to_cart(ra, dec):
#     """Find the cartesian co-ordinates on the unit sphere given the eq. co-ords.
# 
#         ra, dec should be in degrees.
#     """
#     return (math.cos(math.radians(dec)) * math.cos(math.radians(ra)),  # Cartesian x
#             math.cos(math.radians(dec)) * math.sin(math.radians(ra)),  # Cartesian y
#             math.sin(math.radians(dec)))  # Cartesian z


import itertools
import logging
import math
import tkp.db
from datetime import datetime
from tkp.db.alchemy.image import insert_dataset as alchemy_insert_dataset
from tkp.db.generic import columns_from_table
from tkp.utility import substitute_inf
from tkp.utility.coordinates import alpha_inflate
from tkp.utility.coordinates import eq_to_cart
 WHERE ax.runcat IN (SELECT runcat
                       FROM assocxtrsource
                      WHERE xtrsrc = %(xtrsrc)s
                    )
   AND ax.xtrsrc = ex.id
   AND ex.image = im.id
   AND bd.id = im.band
ORDER BY im.taustart_ts
"""

update_dataset_process_end_ts_query = """
UPDATE dataset
   SET process_end_ts = %(end)s
 WHERE id = %(dataset_id)s
"""

def update_dataset_process_end_ts(dataset_id):
    """Update dataset start-of-processing timestamp.

    """
    args = {'dataset_id': dataset_id, 'end': datetime.now()}
    tkp.db.execute(update_dataset_process_end_ts_query, args, commit=True)
    return dataset_id


def insert_dataset(description):
    """
    Insert dataset with description as given by argument.
    """
    db = tkp.db.Database()

# Path: tkp/db/alchemy/image.py
# def insert_dataset(session, description):
#     rerun = session.query(func.max(Dataset.rerun)). \
#         select_from(Dataset).  \
#         filter(Dataset.description == "description"). \
#         one()[0]
# 
#     if not rerun:
#         rerun = 0
#     else:
#         rerun += 1
# 
#     dataset = Dataset(rerun=rerun,
#                       process_start_ts=datetime.now(),
#                       description=description)
#     session.add(dataset)
#     return dataset
# 
# Path: tkp/db/generic.py
# def columns_from_table(table, keywords=None, alias=None, where=None,
#                        order=None):
#     """Obtain specific column (keywords) values from 'table', with
#     kwargs limitations.
# 
#     A very simple helper function, that builds an SQL query to obtain
#     the specified columns from 'table', and then executes that
#     query. Optionally, the WHERE clause can be specified using the
#     where dictionary. It returns a list of a
#     dict (with the originally supplied keywords as dictionary keys),
#     which can be empty.
# 
#     Example:
# 
#         >>> columns_from_table('image', \
#             keywords=['taustart_ts', 'tau_time', 'freq_eff', 'freq_bw'], where={'imageid': 1})
#             [{'freq_eff': 133984375.0, 'taustart_ts': datetime.datetime(2010, 10, 9, 9, 4, 2), 'tau_time': 14400.0, 'freq_bw': 1953125.0}]
# 
#         This builds the SQL query:
#         "SELECT taustart_ts, tau_time, freq_eff, freq_bw FROM image WHERE imageid=1"
# 
#     This function is implemented mainly to abstract and hide the SQL
#     functionality from the Python interface.
# 
#     Args:
# 
#         conn: database connection object
# 
#         table (string): database table name
# 
#     Kwargs:
# 
#         keywords (uple): column names to select from the table. None indicates all ('*')
# 
#         where (dict): where clause for the query, specified as a set
#             of 'key = value' comparisons. Comparisons are and-ed
#             together. Obviously, only 'is equal' comparisons are
#             possible.
# 
#         alias (dict): Chosen aliases for the column names,
#                     used when constructing the returned list of dictionaries
#                     
#         order (string): ORDER BY key.
# 
#     Returns:
# 
#         (tuple): list of dicts. Each dict contains the given keywords,
#             or all if keywords=None. Each element of the list
#             corresponds to a table row.
# 
#     """
#     if keywords is None:
#         query = "SELECT * FROM " + table
#     else:
#         query = "SELECT " + ", ".join(keywords) + " FROM " + table
#     if where is None:
#         where = {}
#     where_args = tuple(where.itervalues())
#     where = " AND ".join(["%s=%%s" % key for key in where.iterkeys()])
#     if where:
#         query += " WHERE " + where
#     if order:
#         query += " ORDER BY " + order
# 
#     cursor = tkp.db.execute(query, where_args)
#     results = cursor.fetchall()
#     results_dict = convert_db_rows_to_dicts(results, alias_map=alias)
#     return results_dict
# 
# Path: tkp/utility/coordinates.py
# def alpha_inflate(theta, decl):
#     """Compute the ra expansion for a given theta at a given declination
#     
#     Keyword arguments:
#     theta, decl are both in decimal degrees.
#     
#     Return value:
#     alpha -- RA inflation in decimal degrees
# 
#     For a derivation, see MSR TR 2006 52, Section 2.1
#     http://research.microsoft.com/apps/pubs/default.aspx?id=64524
# 
#     """
#     if abs(decl) + theta > 89.9:
#         return 180.0
#     else:
#         return math.degrees(abs(math.atan(math.sin(math.radians(theta)) / math.sqrt(abs(math.cos(math.radians(decl - theta)) * math.cos(math.radians(decl + theta)))))))
# 
# Path: tkp/utility/coordinates.py
# def eq_to_cart(ra, dec):
#     """Find the cartesian co-ordinates on the unit sphere given the eq. co-ords.
# 
#         ra, dec should be in degrees.
#     """
#     return (math.cos(math.radians(dec)) * math.cos(math.radians(ra)),  # Cartesian x
#             math.cos(math.radians(dec)) * math.sin(math.radians(ra)),  # Cartesian y
#             math.sin(math.radians(dec)))  # Cartesian z


# Path: tkp/db/general.py
import itertools
import logging
import math
import tkp.db
from datetime import datetime
from tkp.db.alchemy.image import insert_dataset as alchemy_insert_dataset
from tkp.db.generic import columns_from_table
from tkp.utility import substitute_inf
from tkp.utility.coordinates import alpha_inflate
from tkp.utility.coordinates import eq_to_cart

 WHERE ax.runcat IN (SELECT runcat
                       FROM assocxtrsource
                      WHERE xtrsrc = %(xtrsrc)s
                    )
   AND ax.xtrsrc = ex.id
   AND ex.image = im.id
   AND bd.id = im.band
ORDER BY im.taustart_ts
"""

update_dataset_process_end_ts_query = """
UPDATE dataset
   SET process_end_ts = %(end)s
 WHERE id = %(dataset_id)s
"""

def update_dataset_process_end_ts(dataset_id):
    """Update dataset start-of-processing timestamp.

    """
    args = {'dataset_id': dataset_id, 'end': datetime.now()}
    tkp.db.execute(update_dataset_process_end_ts_query, args, commit=True)
    return dataset_id


def insert_dataset(description):
    """
    Insert dataset with description as given by argument.
    """
    db = tkp.db.Database()

    dataset = alchemy_insert_dataset(db.session, description)