import requests
import json
import sys
# import related models here
from requests.auth import HTTPBasicAuth
from .models import CarDealer, DealerReview, CarModel, CarMake
from ibm_watson import NaturalLanguageUnderstandingV1
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
from ibm_watson.natural_language_understanding_v1 import Features, EntitiesOptions, KeywordsOptions

authenticator = IAMAuthenticator('FIarxpFXjQpGduLN3au2LPfISpqKavXibkjOk7GtnAFp')
natural_language_understanding = NaturalLanguageUnderstandingV1(version='2020-08-01',authenticator=authenticator)

natural_language_understanding.set_service_url('https://api.us-south.natural-language-understanding.watson.cloud.ibm.com/instances/d5fd4177-3991-433a-9b70-cb6b05b80ef0')

# Create a `get_request` to make HTTP GET requests
# e.g., response = requests.get(url, params=params, headers={'Content-Type': 'application/json'},
#                                     auth=HTTPBasicAuth('apikey', api_key))
def get_request(url, **kwargs):
    print(kwargs)
    print("GET from {} ".format(url))   
    try:
        response = requests.get(url, headers={'Content-Type': 'application/json'}, params=kwargs)

    except:
        # If any error occurs
        print("Network exception occurred")
    status_code = response.status_code
    print("With status {} ".format(status_code))
    json_data = json.loads(response.text)
    return json_data

# Create a `post_request` to make HTTP POST requests
# e.g., response = requests.post(url, params=kwargs, json=payload)
def post_request(url, json_payload, **kwargs):
    print(json_payload)
    print("POST from {} ".format(url))
    try: 
        requests.post(url, params=kwargs, json=json_payload)
    except:
        # If any error occurs
        print("Network exception occurred", sys.exc_info()[0])

# Create a get_dealers_from_cf method to get dealers from a cloud function
# def get_dealers_from_cf(url, **kwargs):
# - Call get_request() with specified arguments
# - Parse JSON results into a CarDealer object list
def get_dealers_from_cf(url, **kwargs):
    results = []
    # Call get_request with a URL parameter
    json_result = get_request(url)
    if json_result:
        # Get the row list in JSON as dealers
        dealers = json_result["entries"]
        # For each dealer object
        for dealer in dealers:
            # Get its content in `doc` object           
            # Create a CarDealer object with values in `doc` object
            if(dealer):
                dealer_obj = CarDealer(address=dealer["address"], city=dealer["city"], full_name=dealer["full_name"],
                                   id=dealer["id"], lat=dealer["lat"], long=dealer["long"],
                                   short_name=dealer["short_name"],
                                   st=dealer["st"], zip=dealer["zip"])
                results.append(dealer_obj)

    return results

def get_dealer_by_id_from_cf(url, dealerId):
    results = []
    json_result = get_request(url,id=dealerId)
    if json_result:
        # Get the row list in JSON as dealers
        dealers = json_result["docs"]
        # For each dealer object
        for dealer in dealers:              
            dealer_obj = CarDealer(address=dealer["address"], city=dealer["city"], full_name=dealer["full_name"],
                                   id=dealer["id"], lat=dealer["lat"], long=dealer["long"],
                                   short_name=dealer["short_name"],
                                   st=dealer["st"], zip=dealer["zip"])
            results.append(dealer_obj)
    return results

# Create a get_dealer_reviews_from_cf method to get reviews by dealer id from a cloud function
def get_dealer_reviews_by_id_from_cf(url, dealerId):
    results = []
    json_result = get_request(url, dealership=dealerId)
    if json_result:
        # Get the row list in JSON as dealers
        reviews = json_result["docs"]
        # For each dealer object
        for review in reviews:
            # Create a CarDealer object with values in `doc` object
            sentiment = analyze_review_sentiments(review["review"])
            if('id' in review):
                review_obj = DealerReview(id = review["id"],dealership=review["dealership"],
                                        name=review["name"],purchase=review["purchase"], review=review["review"],
                                        purchase_date=review["purchase_date"], car_make=review["car_make"],
                                        car_model=review["car_model"], car_year=review["car_year"], sentiment=sentiment )
                results.append(review_obj)

    return results
# - Call get_request() with specified arguments
# - Parse JSON results into a DealerView object list


# Create an `analyze_review_sentiments` method to call Watson NLU and analyze text
def analyze_review_sentiments(text_to_analyze):
    try:    
        response = natural_language_understanding.analyze(
        text=text_to_analyze,
        features=Features(
            entities=EntitiesOptions(emotion=True, sentiment=True, limit=2),
            keywords=KeywordsOptions(emotion=True, sentiment=True, limit=2))).get_result()   

        sentiment = response["keywords"][0]["sentiment"]["label"]
    except:
        return "neutral"    

    return sentiment
# - Call get_request() with specified arguments
# - Get the returned sentiment label such as Positive or Negative

def get_car_models_and_makes_for_dealer(in_dealer_id):
    carmodels = CarModel.objects.filter(dealer_id=in_dealer_id)
    return carmodels