# Path: studio/model.py
# def reset_storage_providers():
# def get_config(config_file=None):
# def get_db_provider(config=None, blocking_auth=True):
# def get_queue(
#         queue_name=None,
#         cloud=None,
#         config=None,
#         logger=None,
#         close_after=None,
#         verbose=10):
# def shutdown_queue(queue, logger=None, delete_queue=True):
# def get_worker_manager(config, cloud=None, verbose=10):
# 
# Path: studio/auth.py
# def get_and_verify_user(request, authtype):
#     if not request.headers or 'Authorization' not in request.headers.keys():
#         return None
# 
#     token = request.headers['Authorization'].split(' ')[-1]
#     if not token or token == 'null':
#         return None
# 
#     authclass = get_auth_class(authtype)
#     if not authclass:
#         return None
# 
#     if request.json:
#         refresh_token = request.json.get('refreshToken')
#     else:
#         refresh_token = None
# 
#     return authclass.verify_token(token, refresh_token)
# 
# def get_auth(
#         config,
#         blocking=True,
#         verbose=logs.DEBUG):
# 
#     global _auth_singleton
#     if _auth_singleton is None:
#         if isinstance(config, dict):
#             auth_class = get_auth_class(config['type'])
#         else:
#             auth_class = get_auth_class(config)
# 
#         if auth_class:
#             _auth_singleton = auth_class(
#                 config,
#                 blocking=blocking,
#                 verbose=verbose
#             )
#         else:
#             return None
#     return _auth_singleton
# 
# Path: studio/util/logs.py
# DEBUG = logging.DEBUG
# INFO = logging.INFO
# ERROR = logging.ERROR
# def get_logger(name):
# def debug(line):
# def error(line):
# def info(line):


import time
import sys
import argparse
import yaml
import json
import socket
import subprocess
import traceback
import six
import os
import requests
from flask import Flask, render_template, request, redirect, abort
from studio import model
from requests.exceptions import ChunkedEncodingError
from .experiment import experiment_from_dict
from .auth import get_and_verify_user, get_auth
from .util import parse_verbosity
from studio.util import logs


@app.route('/api/get_all_experiments', methods=['POST'])
def get_all_experiments():
    tic = time.time()
    get_and_verify_user(request, get_auth_config())

    # TODO check is myuser_id is authorized to do that

    getlogger().info('Getting all experiments')
    users = get_db().get_users()

    experiments = [e for user in users
                   for e in get_db().get_user_experiments(
                       user, blocking=False)]

    status = "ok"
    retval = json.dumps({
        "status": status,
        "experiments": experiments
    })
    toc = time.time()
    getlogger().info('Processed get_user_experiments request in {} s'
                     .format(toc - tic))
    return retval


@app.route('/api/get_projects', methods=['POST'])
def get_projects():
    tic = time.time()

# Path: studio/model.py
# def reset_storage_providers():
# def get_config(config_file=None):
# def get_db_provider(config=None, blocking_auth=True):
# def get_queue(
#         queue_name=None,
#         cloud=None,
#         config=None,
#         logger=None,
#         close_after=None,
#         verbose=10):
# def shutdown_queue(queue, logger=None, delete_queue=True):
# def get_worker_manager(config, cloud=None, verbose=10):
# 
# Path: studio/auth.py
# def get_and_verify_user(request, authtype):
#     if not request.headers or 'Authorization' not in request.headers.keys():
#         return None
# 
#     token = request.headers['Authorization'].split(' ')[-1]
#     if not token or token == 'null':
#         return None
# 
#     authclass = get_auth_class(authtype)
#     if not authclass:
#         return None
# 
#     if request.json:
#         refresh_token = request.json.get('refreshToken')
#     else:
#         refresh_token = None
# 
#     return authclass.verify_token(token, refresh_token)
# 
# def get_auth(
#         config,
#         blocking=True,
#         verbose=logs.DEBUG):
# 
#     global _auth_singleton
#     if _auth_singleton is None:
#         if isinstance(config, dict):
#             auth_class = get_auth_class(config['type'])
#         else:
#             auth_class = get_auth_class(config)
# 
#         if auth_class:
#             _auth_singleton = auth_class(
#                 config,
#                 blocking=blocking,
#                 verbose=verbose
#             )
#         else:
#             return None
#     return _auth_singleton
# 
# Path: studio/util/logs.py
# DEBUG = logging.DEBUG
# INFO = logging.INFO
# ERROR = logging.ERROR
# def get_logger(name):
# def debug(line):
# def error(line):
# def info(line):


# Path: studio/apiserver.py
import time
import sys
import argparse
import yaml
import json
import socket
import subprocess
import traceback
import six
import os
import requests
from flask import Flask, render_template, request, redirect, abort
from studio import model
from requests.exceptions import ChunkedEncodingError
from .experiment import experiment_from_dict
from .auth import get_and_verify_user, get_auth
from .util import parse_verbosity
from studio.util import logs



@app.route('/api/get_all_experiments', methods=['POST'])
def get_all_experiments():
    tic = time.time()
    get_and_verify_user(request, get_auth_config())

    # TODO check is myuser_id is authorized to do that

    getlogger().info('Getting all experiments')
    users = get_db().get_users()

    experiments = [e for user in users
                   for e in get_db().get_user_experiments(
                       user, blocking=False)]

    status = "ok"
    retval = json.dumps({
        "status": status,
        "experiments": experiments
    })
    toc = time.time()
    getlogger().info('Processed get_user_experiments request in {} s'
                     .format(toc - tic))
    return retval


@app.route('/api/get_projects', methods=['POST'])
def get_projects():
    tic = time.time()

    get_and_verify_user(request, get_auth_config())