"""
Faraday Penetration Test IDE
Copyright (C) 2016  Infobyte LLC (https://faradaysec.com/)
See the file 'doc/LICENSE' for the license information
"""

# Standard library imports
import logging

# Related third party imports
import requests
import flask
from flask import Blueprint, abort, make_response, jsonify
from flask_classful import route
from marshmallow import Schema

# Local application imports
from faraday.server.api.base import GenericView
from faraday.server.utils.web import gzipped

exploits_api = Blueprint('exploits_api', __name__)

logger = logging.getLogger(__name__)


class EmptySchema(Schema):
    pass


class ExploitsView(GenericView):
    route_base = 'vulners/exploits'
    schema_class = EmptySchema

    @gzipped
    @route('<cveid>', methods=['GET'])
    def get_exploits(self, cveid):
        """
        ---
        get:
          tags: ["Vulnerability"]
          description: Use Vulns API to get all exploits available for a specific CVE-ID
          responses:
            200:
              description: Ok
        """
        json_response = None

        logger.debug(
            f"Request parameters: {flask.request.args!r}")

        headers = {
            "Content-Type": "application/json",
            "Accept": "application/json"}

        response = requests.get(
            "https://vulners.com/api/v3/search/id/?references=True&id=" + cveid,
            headers=headers,
            timeout=3
        )

        try:

            json_response = {
                "metasploit": [],
                "exploitdb": [],
                "cveid": cveid
            }

            if response.status_code == 200:

                obj_response = response.json()

                if obj_response["data"]["references"] is not {}:

                    metasploit_modules = obj_response["data"]["references"][cveid].get("metasploit", [])
                    exploitdb_modules = obj_response["data"]["references"][cveid].get("exploitdb", [])

                    for module in metasploit_modules:
                        obj_module = {}
                        obj_module.update({"title": module["title"]})
                        obj_module.update({"id": module["id"]})
                        obj_module.update({"href": module["href"]})
                        json_response["metasploit"].append(obj_module)

                    for module in exploitdb_modules:
                        obj_module = {}
                        obj_module.update({"title": module["title"]})
                        obj_module.update({"id": module["id"]})
                        obj_module.update({"href": module["href"]})
                        json_response["exploitdb"].append(obj_module)

        except KeyError as ex:
            abort(make_response(jsonify(message=f'Could not find {str(ex)}'), 400))

        return flask.jsonify(json_response)


ExploitsView.register(exploits_api)
