from datetime import datetime, timedelta

from .models import *
import json


def get_order_status(order):
    from BaseModels.pay_systems.DVL_Group_kaz.api.funcs import get_order_status
    res_status = None

    if not order or not order.bank_order_id:
        return order

    try:
        res_data = get_order_status(order.bank_order_id)

        res = json.loads(res_data.text)
        res = res['orders'][0]
        order.json_data['status'] = res

        order.status = res['status']


        # if res['amount'] == res['amount_charged'] and res['status'] == 'charged':
        order.save()
        # return order.status


    except Exception as e:
        msg = f'Exception get_order_status = {str(e)}'
        if order:
            msg = f'Exception get_order_status (data = {str(order.id)}) = {str(e)}'
        print(msg)

    return order

def get_orders_for_user(user):

    orders = SubscribeOrder.objects.filter(
        enable=True,
        user=user,
        subscribe_for_user=None,
        createDT__gt=datetime.now() - timedelta(hours=1)
    ).order_by('subscribe', '-createDT').distinct('subscribe')

    SubscribeOrder.objects.filter(
        user=user
    ).exclude(
        id__in=orders.values_list('id', flat=True)
    ).update(enable=False)

    return orders


def create_subscribe_order(data):
    order = None

    try:

        order = SubscribeOrder.objects.create(**data)

        from GeneralApp.funcs_options import get_options_by_opt_types, get_mail_send_options
        sets = get_options_by_opt_types(['domain', 'project_name'], only_vals=True)

        from BaseModels.pay_systems.DVL_Group_kaz.api.funcs import create_order
        data = {
            'currency': data['currency'],
            'amount': data['sum'],
            'description': f'Заказ {order.id} на подписку '
                           f'{data["subscribe"].name} '
                           f'для пользователя {data["user"].username}',
            'options': {
                'auto_charge': 1,
                'return_url': f'{sets["domain"]}/profile/page/my_subscribe/'
            }
        }

        res_data = create_order(data)

        order.pay_page = res_data.headers.get('location')

        res = json.loads(res_data.text)
        res = res['orders'][0]
        order.json_data['create_order'] = res

        order.modifiedDT = datetime.strptime(res['updated'], '%Y-%m-%d %H:%M:%S')
        order.status = res['status']
        order.bank_order_id = res['id']
        if 'segment' in res:
            order.segment = res['segment']
        if 'merchant_order_id' in res:
            order.merchant_order_id = res['merchant_order_id']
        order.save()


    except Exception as e:
        msg = f'Exception create_subscribe_order (data = {str(data)}) = {str(e)}'
        print(msg)

    return order