import copy
import json

from ..api.paths import (
    COMPOUNDS_PATH,
    LIVE_REPORTS_PATH,
)
from ..client import LDClient
from .experimental_models import (
    QueryCondition,)


class ExperimentalLDClient(LDClient):
    """
    NOTE: This is an internal component of ldclient and interfacing with it directly is NOT fully supported

    Functions in the package are
     1. NEW
     2. NOT well tested,
     3. and, MAY break

    Also, these functions may break on upgrades.
    """

    def update_lr_query_and_search_compounds(self, live_report_id, project_id, conditions,
                                             expression):
        """
        Update the LR query based on the specified conditions and expression.
        Subsequently do an advanced search query on the LR.
        Note: The search result will exclude the entity IDs already present in the LR.

        :type live_report_id: str
        :param live_report_id: live report id

        :type conditions: List of :class:`experimental_models.QueryCondition`
        :param conditions: list of query conditions for search

        :type expression: str
        :param expression: Advanced query expression

        :return: List of compound ids that match the search
        """

        new_conditions = QueryCondition.as_list(conditions)
        query_conditions = []
        for condition in new_conditions:
            query_condition = copy.deepcopy(condition)
            query_condition["inverted"] = False
            if (condition.get("type") == "observation"):
                query_condition["create_assay_limited_addable_column"] = False
                query_condition["delimiter"] = "__DEBUG__"
                query_condition["observation_date_inverted"] = False
                query_condition["operator"] = "="
                query_condition["related_column_conditions"] = []
            query_conditions.append(query_condition)
        current_query = self.client.get(service_path=LIVE_REPORTS_PATH,
                                        path='/{0}/query'.format(live_report_id))
        current_query["conditions"] = query_conditions
        current_query["expression"] = expression
        self.client.put(service_path=LIVE_REPORTS_PATH,
                        path='/{0}/query'.format(live_report_id),
                        data=json.dumps(current_query))

        search_request = {
            "compound_search_type": "ADVANCED_QUERY_SEARCH",
            "project_id": project_id,
            "live_report_id": live_report_id,
        }
        response = self.client.post(service_path=COMPOUNDS_PATH,
                                    path='/search',
                                    data=json.dumps(search_request))
        return [compound["id"] for compound in response["results"]]
