import os
import requests
import json
from aggregation_api import base_directory,AggregationAPI
from csv_output import CsvOut
import yaml
import rollbar
import traceback


def aggregate(project_id, token, href, metadata, environment):
    with AggregationAPI(project_id, environment=environment) as project:
        project.__migrate__()
        project.__aggregate__()

        with CsvOut(project) as writer:
            rollbar.report_message("step3","info")
            tarpath = writer.__write_out__(compress=True)
            response = send_uploading(metadata, token, href)
            url = response.json()["media"][0]["src"]
            with open(tarpath, 'rb') as tarball:
                requests.put(url, headers={'Content-Type': 'application/x-gzip'}, data=tarball)
            os.remove(tarpath)
            send_finished(metadata, token, href)


def get_etag(href, token):
    response = requests.get(href, headers=headers(token), params={'admin': True})
    return response.headers['ETag']

def send_uploading(metadata, token, href):
    metadata['state'] = 'uploading'
    body = { 'media': { 'metadata': metadata } }
    return send_request(body, token, href)

def send_finished(metadata, token, href):
    metadata['state'] = 'finished'
    body = { 'media': { 'metadata': metadata } }
    return send_request(body, token, href)

def headers(token, etag=False):
    headers = { 'Accept': 'application/vnd.api+json; version=1',
                'Content-Type': 'application/json',
                'Authorization': 'Bearer '+str(token) }
    if etag:
        headers['If-Match'] = get_etag(etag, token)
    return headers

def send_request(body, token, href):
    body['admin'] = True
    return requests.put(href, headers=headers(token, etag=href), data=json.dumps(body))






@@ -135,23 +135,8 @@
 aml%0A
-import rollbar%0A
 impo
@@ -149,17 +149,16 @@
 ceback%0A%0A
-%0A
 def aggr
@@ -392,59 +392,8 @@
 er:%0A
-            rollbar.report_message(%22step3%22,%22info%22)%0A
     
@@ -786,17 +786,16 @@
  href)%0A%0A
-%0A
 def get_
@@ -1714,13 +1714,8 @@
 (body))%0A
-%0A%0A%0A%0A%0A

remove rollbar completely from jobs