#!/usr/bin/env python3

"""loading.py: /loading API endpoint"""
__author__      = "Radek Hranicky"

import logging

from flask import request, current_app
from flask_restx import Resource, fields

from api.apiConfig import api

loading_start_model = api.model('loading_status',
{
    "started": fields.Boolean()
})

loading_status_model = api.model('loading_status',
{
    "loading": fields.Boolean()
})

loading_last_result_model = api.model('loading_last_result',
{
    "success": fields.Boolean(),
    "error_description": fields.String(),
    "offense_sources_new": fields.Integer(),
    "offense_sources_updated": fields.Integer(),
    "offense_sources_total": fields.Integer(),
    "domain_ip_mappings_new": fields.Integer(),
    "domain_ip_mappings_total": fields.Integer(),
    "unique_domains_new": fields.Integer(),
    "unique_domains_total": fields.Integer()
})

loading_result_model = api.model('loading_result',
{
    "last_result": fields.Nested(loading_last_result_model)
})

from api.apiConfig import api
from database import db
#from database.models import OffenseSource
from database.models import *


log = logging.getLogger(__name__)
ns = api.namespace('loading', description='Loading data from QRadar')


logger = logging.getLogger('domainradar')

@ns.route('/start')
class loadingStart(Resource):
    @api.marshal_with(loading_start_model)
    def get(self):
        """
        Starts the QRadar data loading process
        """
        if not current_app.config['DR']['QLOADER'].isLoading():
            current_app.config['DR']['QLOADER'].startLoading()
            return {
                'started': True
            }
        else:
            # Loading already in progress
            return {
                'started': False
            }
            pass

@ns.route('/status')
class loadingStatus(Resource):
    @api.marshal_with(loading_status_model)
    def get(self):
        """
        Gets status of the QRadar data loading process
        """
        if current_app.config['DR']['QLOADER'].isLoading():
            return {
                'loading': True
            }
        else:
            return {
                'loading': False
            }


@ns.route('/result')
class loadingResult(Resource):
    @api.marshal_with(loading_result_model)
    def get(self):
        """
        Returns the result of the last loading
        """
        return {
            'last_result': current_app.config['DR']['QLOADER'].getLastResult()
        }
