# Path: mass_flask_core/models/analysis_system_instance.py
# class AnalysisSystemInstance(db.Document, AbstractAuthEntity):
#     @property
#     def is_authenticated(self):
#         return True
# 
#     def get_roles(self):
#         return ['analysis_system_instance']
# 
#     @property
#     def max_tlp_level(self):
#         return TLPLevelField.TLP_LEVEL_WHITE
# 
#     analysis_system = ReferenceField(AnalysisSystem, required=True)
#     uuid = StringField(max_length=36, required=True, unique=True, default=_gen_uuid)
#     last_seen = DateTimeField()
# 
#     meta = {
#         'ordering': ['analysis_system', 'uuid'],
#         'indexes': [('analysis_system', 'uuid')]
#     }
# 
#     def __repr__(self):
#         return '[AnalysisSystemInstance] {} {}'.format(self.analysis_system.identifier_name, self.uuid)
# 
#     def __str__(self):
#         return self.__repr__()
# 
#     def update_last_seen(self):
#         self.last_seen = TimeFunctions.get_timestamp()
#         self.save()
# 
#     @property
#     def is_online(self):
#         if self.last_seen is None:
#             return False
# 
#         difference = TimeFunctions.get_timestamp() - self.last_seen
#         return difference < datetime.timedelta(minutes=10)
# 
# Path: mass_flask_core/models/analysis_request.py
# class AnalysisRequest(db.Document):
#     analysis_system = ReferenceField(AnalysisSystem, required=True)
#     sample = ReferenceField(Sample, required=True)
#     analysis_requested = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
#     priority = IntField(default=0, required=True)
# 
#     meta = {
#         'ordering': ['-analysis_requested'],
#         'indexes': ['analysis_requested']
#     }
# 
#     def __repr__(self):
#         return '[AnalysisRequest] {} on {}'.format(self.sample.id, self.analysis_system.identifier_name)
# 
#     def __str__(self):
#         return self.__repr__()
# 
# Path: mass_flask_core/models/scheduled_analysis.py
# class ScheduledAnalysis(db.Document):
#     analysis_system_instance = ReferenceField(AnalysisSystemInstance, required=True)
#     sample = ReferenceField(Sample, required=True)
#     analysis_scheduled = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
#     priority = IntField(default=0, required=True)
# 
#     meta = {
#         'ordering': ['-analysis_scheduled'],
#         'indexes': ['analysis_scheduled']
#     }
# 
#     # @staticmethod
#     # def get_count_for_instance(instance):
#     #     analyses_count = ScheduledAnalysis.objects(analysis_system_instance=instance).count()
#     #     return analyses_count
# 
#     # @staticmethod
#     # def get_count_for_all_instances():
#     #     instance_counts = dict()
#     #     for item in AnalysisSystemInstance.objects:
#     #         instance_counts[item] = 0
#     #     for item in ScheduledAnalysis.objects:
#     #         instance_counts[item.analysis_system_instance] += 1
#     #     return instance_counts
# 
# Path: mass_flask_config/app.py
# BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# SECRET_FILE = os.path.join(BASE_DIR, 'secret.txt')
# def setup_session_auth(user_loader):
# def setup_key_based_auth(key_loader):
# def unauthorized_callback():


import sys
from flask import current_app
from mass_flask_core.models import AnalysisSystemInstance, ScheduledAnalysis, AnalysisRequest
from mass_flask_config.app import app
    for instance in instance_list:
        if instance.analyses_count < min_count:
            min_count = instance.analyses_count
            min_instance = instance
    return min_instance


def _schedule_analysis(request, instance):
    s = ScheduledAnalysis(analysis_system_instance=instance, sample=request.sample)
    s.save()
    instance.analyses_count += 1


def _schedule_analysis_request(request, instance_dict):
    if request.analysis_system.id not in instance_dict:
        return False

    instances = instance_dict[request.analysis_system.id]

    if len(instances) == 0:
        return False

    min_instance = _get_instance_with_minimum_count(instances)
    _schedule_analysis(request, min_instance)
    if min_instance.analyses_count > current_app.config['MAX_SCHEDULE_THRESHOLD']:
        instances.remove(min_instance)
    return True


def schedule_analyses():

# Path: mass_flask_core/models/analysis_system_instance.py
# class AnalysisSystemInstance(db.Document, AbstractAuthEntity):
#     @property
#     def is_authenticated(self):
#         return True
# 
#     def get_roles(self):
#         return ['analysis_system_instance']
# 
#     @property
#     def max_tlp_level(self):
#         return TLPLevelField.TLP_LEVEL_WHITE
# 
#     analysis_system = ReferenceField(AnalysisSystem, required=True)
#     uuid = StringField(max_length=36, required=True, unique=True, default=_gen_uuid)
#     last_seen = DateTimeField()
# 
#     meta = {
#         'ordering': ['analysis_system', 'uuid'],
#         'indexes': [('analysis_system', 'uuid')]
#     }
# 
#     def __repr__(self):
#         return '[AnalysisSystemInstance] {} {}'.format(self.analysis_system.identifier_name, self.uuid)
# 
#     def __str__(self):
#         return self.__repr__()
# 
#     def update_last_seen(self):
#         self.last_seen = TimeFunctions.get_timestamp()
#         self.save()
# 
#     @property
#     def is_online(self):
#         if self.last_seen is None:
#             return False
# 
#         difference = TimeFunctions.get_timestamp() - self.last_seen
#         return difference < datetime.timedelta(minutes=10)
# 
# Path: mass_flask_core/models/analysis_request.py
# class AnalysisRequest(db.Document):
#     analysis_system = ReferenceField(AnalysisSystem, required=True)
#     sample = ReferenceField(Sample, required=True)
#     analysis_requested = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
#     priority = IntField(default=0, required=True)
# 
#     meta = {
#         'ordering': ['-analysis_requested'],
#         'indexes': ['analysis_requested']
#     }
# 
#     def __repr__(self):
#         return '[AnalysisRequest] {} on {}'.format(self.sample.id, self.analysis_system.identifier_name)
# 
#     def __str__(self):
#         return self.__repr__()
# 
# Path: mass_flask_core/models/scheduled_analysis.py
# class ScheduledAnalysis(db.Document):
#     analysis_system_instance = ReferenceField(AnalysisSystemInstance, required=True)
#     sample = ReferenceField(Sample, required=True)
#     analysis_scheduled = DateTimeField(default=TimeFunctions.get_timestamp, required=True)
#     priority = IntField(default=0, required=True)
# 
#     meta = {
#         'ordering': ['-analysis_scheduled'],
#         'indexes': ['analysis_scheduled']
#     }
# 
#     # @staticmethod
#     # def get_count_for_instance(instance):
#     #     analyses_count = ScheduledAnalysis.objects(analysis_system_instance=instance).count()
#     #     return analyses_count
# 
#     # @staticmethod
#     # def get_count_for_all_instances():
#     #     instance_counts = dict()
#     #     for item in AnalysisSystemInstance.objects:
#     #         instance_counts[item] = 0
#     #     for item in ScheduledAnalysis.objects:
#     #         instance_counts[item.analysis_system_instance] += 1
#     #     return instance_counts
# 
# Path: mass_flask_config/app.py
# BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# SECRET_FILE = os.path.join(BASE_DIR, 'secret.txt')
# def setup_session_auth(user_loader):
# def setup_key_based_auth(key_loader):
# def unauthorized_callback():


# Path: mass_flask_scheduling/tasks/schedule_analyses.py
import sys
from flask import current_app
from mass_flask_core.models import AnalysisSystemInstance, ScheduledAnalysis, AnalysisRequest
from mass_flask_config.app import app

    for instance in instance_list:
        if instance.analyses_count < min_count:
            min_count = instance.analyses_count
            min_instance = instance
    return min_instance


def _schedule_analysis(request, instance):
    s = ScheduledAnalysis(analysis_system_instance=instance, sample=request.sample)
    s.save()
    instance.analyses_count += 1


def _schedule_analysis_request(request, instance_dict):
    if request.analysis_system.id not in instance_dict:
        return False

    instances = instance_dict[request.analysis_system.id]

    if len(instances) == 0:
        return False

    min_instance = _get_instance_with_minimum_count(instances)
    _schedule_analysis(request, min_instance)
    if min_instance.analyses_count > current_app.config['MAX_SCHEDULE_THRESHOLD']:
        instances.remove(min_instance)
    return True


def schedule_analyses():

    with app.app_context():