import json
import os

from elasticsearch import Elasticsearch
from src.services.monitor.decorators.monitor_log import logging_endpoint


class ElasticQuery:
    def __init__(self):
        self.client = ElasticQuery.connect_to_elastic()[0]
        # self.client = Elasticsearch("http://10.6.71.62:9200")
        self.final_query = {'query': {}}
        self.final_query['query']['bool'] = {}
        self.final_query['query']['bool']['must'] = []

    @staticmethod
    @logging_endpoint
    def connect_to_elastic():
        CLIENT_URI = os.environ.get('ELASTIC_URI') if os.environ.get('ELASTIC_URI') else \
            os.environ.get('ELASTIC_URI', 'http://10.6.71.62:9200')
        client = Elasticsearch(CLIENT_URI)
        if not client.ping():
            return client, 400
        return client, 200

    def send(self, index):
        resp = self.client.search(
            index=index,
            body=self.final_query
        )
        return resp['hits']['total']['value'], resp['hits']['hits']

    def match_from_timestamp(self, early_ts, late_ts):
        # 'gte': '2022-04-22T11:13:28',
        # 'lte': '2022-04-22T11:14:03'
        self.match_from_field('timestamp', early_ts, late_ts)
        return self

    def match_from_field(self, field, early_ts, late_ts):
        condition = {'range': {field: {'gte': early_ts,
                                       'lte': late_ts}}}
        self.final_query['query']['bool']['must'].append(condition)
        return self

    def match_from_method(self, field, early_ts, late_ts):
        condition = {'range': {field: {'gte': early_ts,
                                       'lte': late_ts}}}
        self.final_query['query']['bool']['must'].append(condition)
        return self

    @staticmethod
    def from_string(query_str):
        query = ElasticQuery()
        query.final_query = json.loads(query_str)
        return query
