# Path: doorman/database.py
# class CRUDMixin(object):
# class Model(CRUDMixin, db.Model):
# class SurrogatePK(object):
#     def create(cls, **kwargs):
#     def update(self, commit=True, **kwargs):
#     def save(self, commit=True):
#     def delete(self, commit=True):
#     def get_by_id(cls, record_id):
# def reference_col(tablename, nullable=False, pk_name='id', **kwargs):
# 
# Path: doorman/models.py
# class Tag(SurrogatePK, Model):
# class Query(SurrogatePK, Model):
# class Pack(SurrogatePK, Model):
# class Node(SurrogatePK, Model):
# class FilePath(SurrogatePK, Model):
# class ResultLog(SurrogatePK, Model):
# class StatusLog(SurrogatePK, Model):
# class DistributedQuery(SurrogatePK, Model):
# class DistributedQueryTask(SurrogatePK, Model):
# class DistributedQueryResult(SurrogatePK, Model):
# class Rule(SurrogatePK, Model):
# class User(UserMixin, SurrogatePK, Model):
#     def __init__(self, value, **kwargs):
#     def __repr__(self):
#     def packs_count(self):
#     def nodes_count(self):
#     def queries_count(self):
#     def file_paths_count(self):
#     def __init__(self, name, query=None, sql=None, interval=3600, platform=None,
#                  version=None, description=None, value=None, removed=True,
#                  shard=None, **kwargs):
#     def __repr__(self):
#     def to_dict(self):
#     def __init__(self, name, platform=None, version=None,
#                  description=None, shard=None, **kwargs):
#     def __repr__(self):
#     def to_dict(self):
#     def __init__(self, host_identifier, node_key=None,
#                  enroll_secret=None, enrolled_on=None, last_checkin=None,
#                  is_active=True, last_ip=None,
#                  **kwargs):
#     def __repr__(self):
#     def get_config(self, **kwargs):
#     def get_new_queries(self, **kwargs):
#     def display_name(self):
#     def packs(self):
#     def queries(self):
#     def file_paths(self):
#     def to_dict(self):
#     def __init__(self, category=None, target_paths=None, *args, **kwargs):
#     def to_dict(self):
#     def get_paths(self):
#     def set_paths(self, *target_paths):
#     def __init__(self, name=None, action=None, columns=None, timestamp=None,
#                  node=None, node_id=None, **kwargs):
#     def __table_args__(cls):
#     def __init__(self, line=None, message=None, severity=None,
#                  filename=None, created=None, node=None, node_id=None,
#                  version=None, **kwargs):
#     def __table_args__(cls):
#     def __init___(self, sql, description=None, not_before=None):
#     def __init__(self, node=None, node_id=None,
#                  distributed_query=None, distributed_query_id=None):
#     def __table_args__(cls):
#     def __init__(self, columns, distributed_query=None, distributed_query_task=None):
#     def __init__(self, name, alerters, description=None, conditions=None, updated_at=None):
#     def template(self):
#     def __init__(self, username, password=None, email=None, social_id=None,
#                  first_name=None, last_name=None):
#     def set_password(self, password):
#     def check_password(self, value):
#     NEW = 0
#     PENDING = 1
#     COMPLETE = 2
#     FAILED = 3


from collections import namedtuple
from operator import itemgetter
from os.path import basename, join, splitext
from flask import current_app, flash
from jinja2 import Markup, Template
from doorman.database import db
from doorman.models import (
    DistributedQuery, DistributedQueryTask,
    Node, Pack, Query, ResultLog, querypacks,
)
import datetime as dt
import json
import pkg_resources
import sqlite3
import string
import threading
import six

def assemble_schedule(node):
    schedule = {}
    for query in node.queries.options(db.lazyload('*')):
        schedule[query.name] = query.to_dict()
    return schedule


def assemble_packs(node):
    packs = {}
    for pack in node.packs.join(querypacks).join(Query) \
        .options(db.contains_eager(Pack.queries)).all():
        packs[pack.name] = pack.to_dict()
    return packs


def assemble_distributed_queries(node):
    '''
    Retrieve all distributed queries assigned to a particular node
    in the NEW state. This function will change the state of the
    distributed query to PENDING, however will not commit the change.
    It is the responsibility of the caller to commit or rollback on the
    current database session.
    '''
    now = dt.datetime.utcnow()
    query = db.session.query(DistributedQueryTask) \
        .join(DistributedQuery) \
        .filter(
            DistributedQueryTask.node == node,
            DistributedQueryTask.status == DistributedQueryTask.NEW,

# Path: doorman/database.py
# class CRUDMixin(object):
# class Model(CRUDMixin, db.Model):
# class SurrogatePK(object):
#     def create(cls, **kwargs):
#     def update(self, commit=True, **kwargs):
#     def save(self, commit=True):
#     def delete(self, commit=True):
#     def get_by_id(cls, record_id):
# def reference_col(tablename, nullable=False, pk_name='id', **kwargs):
# 
# Path: doorman/models.py
# class Tag(SurrogatePK, Model):
# class Query(SurrogatePK, Model):
# class Pack(SurrogatePK, Model):
# class Node(SurrogatePK, Model):
# class FilePath(SurrogatePK, Model):
# class ResultLog(SurrogatePK, Model):
# class StatusLog(SurrogatePK, Model):
# class DistributedQuery(SurrogatePK, Model):
# class DistributedQueryTask(SurrogatePK, Model):
# class DistributedQueryResult(SurrogatePK, Model):
# class Rule(SurrogatePK, Model):
# class User(UserMixin, SurrogatePK, Model):
#     def __init__(self, value, **kwargs):
#     def __repr__(self):
#     def packs_count(self):
#     def nodes_count(self):
#     def queries_count(self):
#     def file_paths_count(self):
#     def __init__(self, name, query=None, sql=None, interval=3600, platform=None,
#                  version=None, description=None, value=None, removed=True,
#                  shard=None, **kwargs):
#     def __repr__(self):
#     def to_dict(self):
#     def __init__(self, name, platform=None, version=None,
#                  description=None, shard=None, **kwargs):
#     def __repr__(self):
#     def to_dict(self):
#     def __init__(self, host_identifier, node_key=None,
#                  enroll_secret=None, enrolled_on=None, last_checkin=None,
#                  is_active=True, last_ip=None,
#                  **kwargs):
#     def __repr__(self):
#     def get_config(self, **kwargs):
#     def get_new_queries(self, **kwargs):
#     def display_name(self):
#     def packs(self):
#     def queries(self):
#     def file_paths(self):
#     def to_dict(self):
#     def __init__(self, category=None, target_paths=None, *args, **kwargs):
#     def to_dict(self):
#     def get_paths(self):
#     def set_paths(self, *target_paths):
#     def __init__(self, name=None, action=None, columns=None, timestamp=None,
#                  node=None, node_id=None, **kwargs):
#     def __table_args__(cls):
#     def __init__(self, line=None, message=None, severity=None,
#                  filename=None, created=None, node=None, node_id=None,
#                  version=None, **kwargs):
#     def __table_args__(cls):
#     def __init___(self, sql, description=None, not_before=None):
#     def __init__(self, node=None, node_id=None,
#                  distributed_query=None, distributed_query_id=None):
#     def __table_args__(cls):
#     def __init__(self, columns, distributed_query=None, distributed_query_task=None):
#     def __init__(self, name, alerters, description=None, conditions=None, updated_at=None):
#     def template(self):
#     def __init__(self, username, password=None, email=None, social_id=None,
#                  first_name=None, last_name=None):
#     def set_password(self, password):
#     def check_password(self, value):
#     NEW = 0
#     PENDING = 1
#     COMPLETE = 2
#     FAILED = 3


# Path: doorman/utils.py
from collections import namedtuple
from operator import itemgetter
from os.path import basename, join, splitext
from flask import current_app, flash
from jinja2 import Markup, Template
from doorman.database import db
from doorman.models import (
    DistributedQuery, DistributedQueryTask,
    Node, Pack, Query, ResultLog, querypacks,
)
import datetime as dt
import json
import pkg_resources
import sqlite3
import string
import threading
import six


def assemble_schedule(node):
    schedule = {}
    for query in node.queries.options(db.lazyload('*')):
        schedule[query.name] = query.to_dict()
    return schedule


def assemble_packs(node):
    packs = {}
    for pack in node.packs.join(querypacks).join(Query) \
        .options(db.contains_eager(Pack.queries)).all():
        packs[pack.name] = pack.to_dict()
    return packs


def assemble_distributed_queries(node):
    '''
    Retrieve all distributed queries assigned to a particular node
    in the NEW state. This function will change the state of the
    distributed query to PENDING, however will not commit the change.
    It is the responsibility of the caller to commit or rollback on the
    current database session.
    '''
    now = dt.datetime.utcnow()
    query = db.session.query(DistributedQueryTask) \
        .join(DistributedQuery) \
        .filter(
            DistributedQueryTask.node == node,
            DistributedQueryTask.status == DistributedQueryTask.NEW,

            DistributedQuery.not_before < now,