#!/usr/bin/env python3

"""resolution.py: /resolution 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('resolution', description='Resolution of external data')

logger = logging.getLogger('domainradar')

resolution_start_model = api.model('resolution_start',
{
    "started": fields.Boolean()
})

resolution_status_model = api.model('resolution_status',
{
    "resolving": fields.Boolean()
})

resolution_last_result_model = api.model('resolution_result',
{
    "success": fields.Boolean(),
    "error_description": fields.String(),
    "domains_resolved_new": fields.Integer(),
    "domains_resolved_total": fields.Integer(),
    "domains_remaining": fields.Integer(),
    "domains_total": fields.Integer()
})

resolution_result_model = api.model('resolution_last_result_model',
{
    "last_result": fields.Nested(resolution_last_result_model)
})


@ns.route('/start')
class resolutionStart(Resource):
    @api.marshal_with(resolution_start_model)
    def get(self):
        """
        Starts the resolution of external data
        """
        if not current_app.config['DR']['DATARESOLVER'].isResolving():
            current_app.config['DR']['DATARESOLVER'].startResolving()
            return {
                'started': True
            }
        else:
            # Loading already in progress
            return {
                'started': False
            }
            pass

@ns.route('/status')
class resolutionStatus(Resource):
    @api.marshal_with(resolution_status_model)
    def get(self):
        """
        Gets the status of external data resolution process
        """
        if current_app.config['DR']['DATARESOLVER'].isResolving():
            return {
                'resolving': True
            }
        else:
            return {
                'resolving': False
            }


@ns.route('/result')
class resolutionResult(Resource):
    @api.marshal_with(resolution_result_model)
    def get(self):
        """
        Returns the result of the last data resolution
        """
        return {
            'last_result': current_app.config['DR']['DATARESOLVER'].getLastResult()
        }
