# AUTOGENERATED! DO NOT EDIT! File to edit: 00_downloader.ipynb (unless otherwise specified).

__all__ = ['loadJson', 'saveJson', 'Downloader']

# Cell
import pyrebase
import json
import os
import time
import numpy as np
import pandas as pd

def loadJson(path, default = {}):
    """Return dictionary from json file."""
    if os.path.isfile(path):
        try:
            with open(path, 'r', encoding = 'utf-8') as f:
                return json.loads(f.read(), strict = False)
        except:
            return default
    else:
        return default


def saveJson(data, path):
    """Save dictionary as json file."""
    with open(path, 'w+', encoding = 'utf-8') as f:
        f.write(json.dumps(data, indent=1, sort_keys=True))


class Downloader():
    def __init__(self, google_services_path):
        self.google_services_path = google_services_path
        self.db = self.getDataBase()

    def getDataBase(self):
        google_services = loadJson(self.google_services_path)
        # Configuring firebase
        config = {
            "apiKey": google_services['client'][0]['api_key'][0]['current_key'],
            "authDomain": "%s.firebaseapp.com" % google_services['project_info']['project_id'],
            "databaseURL": google_services['project_info']['firebase_url'],
            "storageBucket": google_services['project_info']['storage_bucket']
        }
        firebase = pyrebase.initialize_app(config)
        db = firebase.database()
        return db

    def download(self, experiment, storage_dir):
        print("Getting pps for: "+experiment)
        pps = self.db.child(experiment).child("pps").shallow().get().val()
        pps = sorted(list(pps))

        for pp in pps:
            #try:
            path = os.path.join(storage_dir, "%s.json"%pp)
            print("Syncing %s" %pp)
            participant = dict(self.db.child(experiment).child("pps/%s" % (pp)).get().val())
            participant['participantId'] = pp
            participant['experiment'] = experiment
            saveJson(participant, path)
            #except:
            #    print("There was a problem with participant %s"%pp)


    def delete_participants(self, experiment):
        try:
            input("Warning: Are you sure you want to delete participants of experiment: %s?\n"%experiment)

            if answer.lower()[0] == 'y':
                pps = sorted(list(self.db.child(experiment).child("pps").shallow().get().val()))
                for pp in pps:
                    #print(pp)
                    self.db.child(experiment).child("pps/%s" % (pp)).remove()
        except:
            print("cound not delete %s"%experiment)