import sqlalchemy as sa


def get_task_type_parameters(session, type_name):
    sql = sa.text("SELECT hstore_to_json(attributes) "
                    "FROM service.task_type "
                    "WHERE name = :type_name")
    result = session.execute(sql, {'type_name' : type_name})
    value = result.scalar()
    if value is not None:
        return value
    return {}


def concatenate_task_type_parameters(session, type_name, dict):
    if len(dict) == 0:
        return

    hstore = "hstore(ARRAY["
    first = True
    for k, v in dict.items():
        if not first:
            hstore += ","
        hstore += "['" + k + "','" + v + "']"
        first = False
    hstore += "])"

    updateSql = sa.text("UPDATE service.task_type "
                        "SET attributes = "
                        "attributes || " + hstore + " "
                        "WHERE name = :type_name")
    result = session.execute(updateSql, {'type_name' : type_name})

    if result.rowcount == 0:
        insertSql = sa.text("INSERT INTO service.task_type "
                            "VALUES (:type_name, " + hstore + ")")
        result = session.execute(insertSql, {'type_name' : type_name})
