#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import os
import warnings
import json
import magic

try:
    import requests
except Exception as excp:
    warnings.warn("requests library is non installed")


class TheHiveApi():

    """
        Python API for TheHive

        :param url: thehive URL
        :param username: username
        :param password: password
    """

    def __init__(self, url, username, password, proxies):

        self.url = url
        self.username = username
        self.password = password
        self.proxies = proxies
        self.session = requests.Session()
        self.auth = requests.auth.HTTPBasicAuth(username=self.username,
                                                password=self.password)

    def create_case(self, case):
        req = self.url + "/api/case"
        data = case.jsonify()
        try:
            return self.session.post(req, headers={'Content-Type': 'application/json'}, data=data, proxies=self.proxies, auth=self.auth)
        except requests.exceptions.RequestException as e:
            sys.exit("Error: {}".format(e))

    def create_case_task(self, id, caseTask):
        req = self.url + "/api/case/{}/task".format(id)
        data = caseTask.jsonify()

        try:
            return self.session.post(req, headers={'Content-Type': 'application/json'}, data=data, proxies=self.proxies, auth=self.auth)
        except requests.exceptions.RequestException as e:
            sys.exit("Error: {}".format(e))

    def create_task_log(self, taskId, caseTaskLog):
        self.proxies = {
            'http':'http://localhost:8080'
        }
        req = self.url + "/api/case/task/{}/log".format(taskId)
        data = {'_json': json.dumps({"message":caseTaskLog.message})}

        if caseTaskLog.file:
            f = {'attachment': ( os.path.basename(caseTaskLog.file), open(caseTaskLog.file, 'rb'), magic.Magic(mime=True).from_file(caseTaskLog.file))}
            try:
                return self.session.post(req, data=data,files=f, proxies=self.proxies, auth=self.auth)
            except requests.exceptions.RequestException as e:
                sys.exit("Error: {}".format(e))

        else:
            try:
                return self.session.post(req, headers={'Content-Type': 'application/json'}, data=json.dumps({'message':caseTaskLog.message}), proxies=self.proxies, auth=self.auth)
            except requests.exceptions.RequestException as e:
                sys.exit("Error: {}".format(e))


    def create_case_observable(self, taskId, CaseObservable):
        


    def get_case(self, id):
        req = self.url + "/api/case/{}".format(id)

        try:
            return self.session.get(req, proxies=self.proxies, auth=self.auth)
        except requests.exceptions.RequestException as e:
            sys.exit("Error: {}".format(e))

    def get_case_observables(self, id):
        req = self.url + "/api/case/artifact/_search"
        data = {
            "query": {
                "_and": [{
                    "_parent": {
                        "_type": "case",
                        "_query": {
                            "_id": id
                        }
                    }
                }, {
                    "status": "Ok"
                }]
            }
        }

        try:
            return self.session.post(req, json=data, proxies=self.proxies, auth=self.auth)
        except requests.exceptions.RequestException as e:
            sys.exit("Error: {}".format(e))

    def get_case_template(self, name):
        req = self.url + "/api/case/template/_search"
        data = {
            "query": {
                "_and": [{
                    "_field": "name",
                    "_value": name
                }, {
                    "status": "Ok"
                }]
            }
        }

        try:
            response = self.session.post(req, json=data, proxies=self.proxies, auth=self.auth)
            jsonResponse = response.json()

            if response.status_code == 200 and len(jsonResponse) > 0:
                return response.json()[0]
            else:
                sys.exit("Error: {}".format("Unable to find case templates"))
        except requests.exceptions.RequestException as e:
            sys.exit("Error: {}".format(e))




# - addObservable(file)
# - addObservable(data)

@@ -1546,86 +1546,8 @@
 g):%0A
-        self.proxies = %7B%0A            'http':'http://localhost:8080'%0A        %7D%0A
     
@@ -1606,16 +1606,16 @@
 taskId)%0A
+
         
@@ -2453,41 +2453,1202 @@
 lf, 
-taskId, CaseObservable):%0A        
+caseId, caseObservable):%0A%0A%0A        req = self.url + %22/api/case/%7B%7D/artifact%22.format(caseId)%0A        obs = %7B%22message%22:caseObservable.message,        %22ioc%22:caseObservable.ioc,%0A            %22tlp%22:caseObservable.tlp,%0A            %22tags%22:caseObservable.tags,%0A            %22dataType%22: caseObservable.dataType%7D%0A        print(obs)%0A        if caseObservable.file:%0A            f = %7B'attachment': ( os.path.basename(caseTaskLog.file), open(caseObservable.file, 'rb'), magic.Magic(mime=True).from_file(caseTaskLog.file))%7D%0A            try:%0A                data = json.dumps(obs)%0A                return self.session.post(req, data=data,files=f, proxies=self.proxies, auth=self.auth)%0A            except requests.exceptions.RequestException as e:%0A                    sys.exit(%22Error: %7B%7D%22.format(e))%0A        else:%0A            try:%0A                obs%5B'data'%5D = %5B%5D%0A                obs%5B'data'%5D.append(caseObservable.data)%0A                data = json.dumps(obs)%0A                return self.session.post(req,headers=%7B'Content-Type': 'application/json'%7D, data=data, proxies=self.proxies, auth=self.auth)%0A            except requests.exceptions.RequestException as e:%0A                    sys.exit(%22Error: %7B%7D%22.format(e))%0A%0A%0A
 %0A%0A%0A 

add observables to TheHive