#!/usr/bin/env python3

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

import logging

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

from api.apiConfig import api

log = logging.getLogger(__name__)
ns = api.namespace('analysis', description='Analysis of domaind names')

logger = logging.getLogger('domainradar')

analysis_start_model = api.model('analysis_start',
{
    "started": fields.Boolean()
})

analysis_status_model = api.model('analysis_status',
{
    "analyzing": fields.Boolean()
})

analysis_last_result_model = api.model('analysis_last_result',
{
    "success": fields.Boolean(),
    "error_description": fields.String(),
    "domains_analyzed_new": fields.Integer(),
    "domains_analyzed_total": fields.Integer(),
    "domains_remaining": fields.Integer(),
    "domains_total": fields.Integer()
})

analysis_result_model = api.model('analysis_result_model',
{
    "last_result": fields.Nested(analysis_last_result_model)
})

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

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


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