from django.http import JsonResponse

import requests
import json
import re

from management.models import Good
from stock.models import ReceiptItem
#### UTILS #################

def get_project_config_by_name(project_name):
    try:
        import os
        file_config = os.path.abspath('config.json')
        with open(file_config, 'r') as f:
            config = json.load(f)
        return config["CONFIG"][project_name]
    except Exception as error:
        raise error

def get_currency_exchange_from_nbu():
    try:
        response_dollar = requests.get('https://bank.gov.ua/NBUStatService/v1/statdirectory/exchange?valcode=USD&json').json()
        exchangeRates_dollar =  response_dollar[0].get('rate')
        exchangedate_dollar = response_dollar[0].get('exchangedate')
        response_euro = requests.get('https://bank.gov.ua/NBUStatService/v1/statdirectory/exchange?valcode=EUR&json').json()
        exchangeRates_euro =  response_euro[0].get('rate')
        exchangedate_euro = response_euro[0].get('exchangedate')
        return exchangeRates_dollar, exchangedate_dollar, exchangeRates_euro, exchangedate_euro
    except Exception as error:
        raise error

def getUnitOfMeasurementByName(request):
    if request.method == "POST":
        data = json.loads(request.body)
        name = data.get('name', '')
        good = Good.objects.get(name=name)
        unit_of_measurement = good.unit_of_measurement
        return JsonResponse({'unit_of_measurement': unit_of_measurement})
    
def checkTmcByNameAndUnitOfMeasurement(request):
    if request.method == "POST":
        data = json.loads(request.body)
        name = data.get('name', '')
        unit_of_measurement = data.get('UnitOfMeasuremen', '')
        if name and unit_of_measurement:
            if Good.objects.filter(name=name, unit_of_measurement=unit_of_measurement).exists():
                return JsonResponse({'result': "ok"})
            else:
                return JsonResponse({'result': "error"})

def addTmcFromReceiptTable(request):
    try:
        data = json.loads(request.body)
        name, quantity, unit_of_measurement, price, total, action = data['data']

        good = Good.objects.create(
                    name = name,
                    unit_of_measurement = unit_of_measurement,
                    created_by = request.user,
                )
        return JsonResponse({'result': "ok"})
    except Exception as error:
        return JsonResponse({'result': "error"})

def split_string_into_name_and_units_of_measurement(string):
    try:
        result = re.search(r'(.+?)>>(.+)', string)
        if result:
            name = result.group(1).strip()
            units_of_measurement = result.group(2).strip()
            return name, units_of_measurement
    except Exception as error:
        raise error 

def remove_spaces_from_string(string):
    try:
        string = re.sub(" +", " ", string)
        return string
    except Exception as error:
        raise error 

def _get_last_price_by_good_name(name):
    try:
        name, unit_of_measurement = split_string_into_name_and_units_of_measurement(name)
        if Good.objects.filter(name = name, unit_of_measurement=unit_of_measurement).exists():
            good = Good.objects.get(name = name, unit_of_measurement=unit_of_measurement)
            price_per_unit = ReceiptItem.objects.filter(good_id = good.id).last()
            if price_per_unit:
                return price_per_unit.price
            else:
                return 0 
        else: 
            return 0 
    except Exception as error:
        raise error

def _get_all_goods_name_with_unit_of_measurement_for_web(request):
    try:
        goods = list(Good.objects.values("name", "unit_of_measurement"))
        return JsonResponse({'message': 'Success', 'data':goods})
    except Exception as error:
        return JsonResponse({'message': 'error','data':str(error)})

def _get_all_goods_name_with_unit_of_measurement():
    try:
        goods = Good.objects.values("name", "unit_of_measurement")
        return goods
    except Exception as error:
        raise error

#### END UTILS #################

def convert_price(price):
    try:
        price = price.replace(',','.')
        price =float(price)

        return price
    except Exception as error:
        raise error
