from app.api import api
from app.models import Mandate
from django.conf import settings

from app.util import datetime_util


class MandateAccessor:
    @classmethod
    def create_mandate(cls, application_id, mandate_id, action, collection, frequency, monthly_frequency,
                       mandate_amount, status, mode, until_cancelled, date_first_collection, date_final_collection, mandate_url=None):
        time_now = datetime_util.get_now_ist_string()

        # mandate, status = Mandate.objects.update_or_create(
        #     consumer_application_id=application_id,
        #     defaults={
        #         "mandate_id": mandate_id,
        #         "action": action,
        #         "collection": collection,
        #         "frequency": frequency,
        #         "monthly_frequency": monthly_frequency,
        #         "mandate_amount": mandate_amount,
        #         "status": status,
        #         "mode": mode,
        #         "mandate_url": mandate_url,
        #         "until_cancelled": until_cancelled,
        #         "date_first_collection": date_first_collection,
        #         "created_at": time_now,
        #         "updated_at": time_now
        #     }
        # )

        mandate = Mandate.objects.create(
            consumer_application_id=application_id,
            mandate_id=mandate_id,
            action=action,
            collection=collection,
            frequency=frequency,
            monthly_frequency=monthly_frequency,
            mandate_amount=mandate_amount,
            status=status,
            mode=mode,
            mandate_url=mandate_url,
            until_cancelled=until_cancelled,
            date_first_collection=date_first_collection,
            expiry_date=date_final_collection,
            created_at=time_now,
            updated_at=time_now
        )

        return api.SUCCESS, mandate

    @classmethod
    def update_mandate_url(cls, application_id, mandate_url):
        time_now = datetime_util.get_now_ist_string()
        Mandate.objects.filter(consumer_application_id=application_id).update(
            mandate_url=mandate_url, updated_at=time_now)

    @classmethod
    def check_mandate_setup_status(cls, application_id):
        mandate = Mandate.objects.filter(consumer_application_id=application_id, status='active').first()

        if not mandate:
            return None

        if mandate.status == "active":
            return True
        else:
            return False
