from cassandra.cluster import Cluster
from model import Record
'''
Module with helper functions to connect, retrieve and save data to Cassandra
'''


def _obtain_session(contact_points, keyspace):
    cluster = Cluster(contact_points)
    return cluster.connect(keyspace)


def read_modified(cassandra, db, column_family, date):
    session = _obtain_session(cassandra, db)
    query = "select * from {cf} where last_modified > '{d}' allow filtering"\
        .format(cf=column_family, d=date.strftime("%Y-%m-%dT%H:%M:%S"))
    return session.execute_async(query)


def fetch(statement):
    return {row.id: Record(row.id, row.last_modified, row.data) for row in statement.result()}


def save_records(cassandra, db, column_family, records, keep_hystory):
    session = _obtain_session(cassandra, db)
    query = "insert into {cf} (id, last_modified, data) values (?, dateOf(now()), ?)".format(cf=column_family)
    prepared_stmt = session.prepare(query)
    for record in records:
        if not keep_hystory:
            delete_record(column_family, record.id_, session)
        bound_stmt = prepared_stmt.bind([record.id_, record.data])
        session.execute(bound_stmt)


def delete_record(column_family, record_id, session):
    query = "delete from {cf} where id = {id}".format(cf=column_family, id=record_id)
    session.execute(query)