from datetime import datetime

from sqlalchemy.orm import sessionmaker

from db.helpers import get_engine
from db.models import Order, OrderStatus, OrderProductsSold  # , ProductsSold
from service.helper import parse_date, get_paged_data
from constants import api_url
import logging
import requests
from service.auth_service import get_auth_token
from pyrate_limiter import Rate, Limiter, Duration


class TrayOrderService:
    access_token = None
    limiter = None

    logger = logging.getLogger(__name__)


    def __init__(self):
        self.limiter = Limiter(Rate(100, Duration.SECOND * 60), max_delay=50000)
        self.access_token = get_auth_token()
        
    def get_complete_order(self, order_id: int):
        url = f"{api_url}/orders/{order_id}/complete?access_token={self.access_token}"        
        response = requests.get(url)        
        return self.parse_complete_order(response.json()['Order'])

    def save_all_orders(self):
        params = {
            'access_token': self.access_token
        }
        json_orders = get_paged_data('orders', 'Orders', self.limiter, max_pages=None, params=params)
        self.save_orders(json_orders)
        
    def parse_complete_order(self, json):
        order = json.get('Order')
        

    def parse_order(self, json_order):
        return Order(
            id=int(json_order.get('id')),
            status=json_order.get('status'),
            date=parse_date(json_order.get('date')),
            customer_id=int(json_order.get('customer_id')),
            partial_total=float(json_order.get('partial_total')),
            taxes=float(json_order.get('taxes')),
            discount=float(json_order.get('discount')),
            point_sale=json_order.get('point_sale'),
            shipment=json_order.get('shipment'),
            shipment_value=float(json_order.get('shipment_value')),
            shipment_date=parse_date(json_order.get('shipment_date')),
            store_note=json_order.get('store_note'),
            discount_coupon=json_order.get('discount_coupon'),
            payment_method_rate=float(json_order.get('payment_method_rate')),
            value_1=float(json_order.get('value_1')),
            payment_form=json_order.get('payment_form'),
            sending_code=json_order.get('sending_code'),
            session_id=json_order.get('session_id'),
            total=float(json_order.get('total')),
            payment_date=parse_date(json_order.get('payment_date')),
            access_code=json_order.get('access_code'),
            #progressive_discount=float(json_order.get('progressive_discount')),
            #shipping_progressive_discount=float(json_order.get('shipping_progressive_discount')),
            shipment_integrator=json_order.get('shipment_integrator'),
            modified=datetime.strptime(json_order.get('modified'), '%Y-%m-%d %H:%M:%S'),
            printed=bool(json_order.get('printed')),
            #interest=float(json_order.get('interest')),
            #cart_additional_values_discount=float(json_order.get('cart_additional_values_discount')),
            #cart_additional_values_increase=float(json_order.get('cart_additional_values_increase')),
            id_quotation=json_order.get('id_quotation'),
            estimated_delivery_date=parse_date(json_order.get('estimated_delivery_date')),
            external_code=json_order.get('external_code'),
            tracking_url=json_order.get('tracking_url'),
            has_payment=bool(int(json_order.get('has_payment'))),
            has_shipment=bool(int(json_order.get('has_shipment'))),
            has_invoice=bool(int(json_order.get('has_invoice'))),
            #total_comission_user=float(json_order.get('total_comission_user')),
            #total_comission=float(json_order.get('total_comission')),
            is_traceable=bool(json_order.get('is_traceable')),
            #order_status_id=int(json_order.get('OrderStatus')['id'])
        )

    def parse_order_status(self, json_order_status):
        return OrderStatus(
            id=int(json_order_status['id']),
            default=bool(int(json_order_status['default'])),
            type=json_order_status['type'],
            show_backoffice=bool(int(json_order_status['show_backoffice'])),
            allow_edit_order=bool(int(json_order_status['allow_edit_order'])),
            status=json_order_status['status'],
            description=json_order_status['description'],
            background=json_order_status['background']
        )

    def parse_order_products_sold(self, json_order_ps, order_id):
        return OrderProductsSold(
            order_id=order_id,
            products_sold_id=json_order_ps['id']
        )

    def save_orders(self, orders):
        for json_order in orders:
            json_order = json_order['Order']

            order = self.parse_order(json_order)

            if 'OrderStatus' in json_order:
                json_order_status = json_order['OrderStatus']
                order_status = self.parse_order_status(json_order_status)
                self.session.merge(order_status)

            if 'ProductsSold' in json_order:
                for json_ps in json_order['ProductsSold']:
                    order_products_sold = self.parse_order_products_sold(json_ps, order.id)
                    self.session.merge(order_products_sold)

            self.session.merge(order)

        self.session.commit()
