from django.core.management.base import BaseCommand, CommandError
from notification.models import (
    NotificationToken,
    NotificationType,
)
from notification.najva.send_notif_to_segments import send_notification_to_specific_segment
from authentication.models import UserMessageType
from authentication.sahandsms.sms import sms_reminder
from panel.models import OperatorLastTimeEnter
from panel.models import FunctionExecutor
from panel.models import *
import schedule
import time
import datetime

from panel.poultry.views import Check_Poultry_Auction_request

TITLE = ""
BODY = ""
CONTENT = ""
LINK_TEXT = ""
LINK = ""


def send_request_notification_to_city_operator():
    if CheckState.objects.filter(state__exact=True):
        for item in CheckState.objects.filter(state__exact=True):
            city_operator_user = UserProfile.objects.get(role__name__exact="CityOperator")
            city_user_token = NotificationToken.objects.get(user__exact=city_operator_user).token
            send_notification_to_specific_segment(
                title=TITLE,
                body=BODY,
                content=CONTENT,
                icon=None,
                image=None,
                subscriber_tokens=[city_user_token],
            )
            notification = Notification(
                title=TITLE,
                content=CONTENT
            )
            notification.notif_type = NotificationType.objects.get(name='poultry')
            notification.notification_user = city_operator_user
            notification.save()
            item.notification = notification
            item.state = False
            item.city_state_notification = True
            item.main_check = "pending"
            item.save()
    if CheckState.objects.filter(state__exact=False):
        for item in CheckState.objects.filter(state__exact=False):
            if item.city_state_notification is True and item.main_check == "pending":
                city_operator_user = UserProfile.objects.get(role__name__exact="CityOperator")
                last_enter_obj = OperatorLastTimeEnter.objects.get(operator__exact=city_operator_user)
                if item.notification.create_date < last_enter_obj.city_operator_last_time_check < item.notification.create_date + datetime.timedelta(
                        hours=5):
                    item.notification.status = "read"
                    item.main_check = "city_end"
                    item.notification.save()
                else:
                    user_message = UserMessage(
                        heading=TITLE,
                        message=CONTENT,
                        link_text=LINK_TEXT,
                        link=LINK,
                    )
                    user_message.message_type = UserMessageType.objects.get(name="modal")
                    user_message.save()
                    user_message.users.add(city_operator_user)
                    item.user_message = user_message
                    item.city_state_notification = False
                    item.city_state_modal = True
                    item.main_check = 'pending'
                    item.save()
    if CheckState.objects.filter(city_state_modal=True, main_check="pending"):
        for item in CheckState.objects.filter(city_state_modal=True, main_check="pending"):
            city_operator_user = UserProfile.objects.get(role__name__exact="CityOperator")
            last_enter_obj = OperatorLastTimeEnter.objects.get(operator__exact=city_operator_user)
            if item.user_message.create_date < last_enter_obj.city_operator_last_time_check < item.user_message.create_date + datetime.timedelta(
                    hours=5):
                item.user_message.state = "read"
                item.main_check = "city_end"
                item.notification.save()
            else:
                sms_reminder(
                    receptor=city_operator_user.mobile,
                    title=TITLE,
                    content=CONTENT,
                    link_text=LINK_TEXT,
                    link=LINK,
                    time=datetime.datetime.now()
                )
                user_message = UserMessage(
                    heading=TITLE,
                    message=CONTENT,
                    link_text=LINK_TEXT,
                    link=LINK,
                )
                user_message.message_type = UserMessageType.objects.get(name="sms")
                user_message.save()
                user_message.users.add(city_operator_user)
                item.user_message = user_message
                item.city_state_modal = False
                item.city_state_sms = True
                item.city_state = True
                item.main_check = "city_end"
                item.save()


def send_request_notification_to_province_operator():
    if CheckState.objects.filter(city_state=True):
        for item in CheckState.objects.filter(city_state=True):
            province_operator_user = UserProfile.objects.get(role__name__exact="ProvinceOperator")
            province_user_token = NotificationToken.objects.get(user__exact=province_operator_user).token
            send_notification_to_specific_segment(
                title=TITLE,
                body=BODY,
                content=CONTENT,
                icon=None,
                image=None,
                subscriber_tokens=[province_user_token],
            )
            notification = Notification(
                title=TITLE,
                content=CONTENT
            )
            notification.notif_type = NotificationType.objects.get(name='poultry')
            notification.notification_user = province_operator_user
            notification.save()
            item.notification = notification
            item.province_state_notification = True
            item.main_check = "pending"
            item.save()
    if CheckState.objects.filter(city_state=True):
        for item in CheckState.objects.filter(city_state=True):
            if item.province_state_notification is True and item.main_check == "pending":
                province_operator_user = UserProfile.objects.get(role__name__exact="ProvinceOperator")
                last_enter_obj = OperatorLastTimeEnter.objects.get(operator__exact=province_operator_user)
                if item.notification.create_date < last_enter_obj.province_operator_last_time_check < item.notification.create_date + datetime.timedelta(
                        hours=5):
                    item.notification.status = "read"
                    item.main_check = "province_end"
                    item.notification.save()
                else:
                    user_message = UserMessage(
                        heading=TITLE,
                        message=CONTENT,
                        link_text=LINK_TEXT,
                        link=LINK,
                    )
                    user_message.message_type = UserMessageType.objects.get(name="modal")
                    user_message.save()
                    user_message.users.add(province_operator_user)
                    item.user_message = user_message
                    item.province_state_notification = False
                    item.province_state_modal = True
                    item.main_check = 'pending'
                    item.save()
    if CheckState.objects.filter(province_state_modal=True, main_check="pending"):
        for item in CheckState.objects.filter(province_state_modal=True, main_check="pending"):
            province_operator_user = UserProfile.objects.get(role__name__exact="ProvinceOperator")
            last_enter_obj = OperatorLastTimeEnter.objects.get(operator__exact=province_operator_user)
            if item.user_message.create_date < last_enter_obj.province_operator_last_time_check < item.user_message.create_date + datetime.timedelta(
                    hours=5):
                item.user_message.state = "read"
                item.main_check = "province_end"
                item.notification.save()
            else:
                sms_reminder(
                    receptor=province_operator_user.mobile,
                    title=TITLE,
                    content=CONTENT,
                    link_text=LINK_TEXT,
                    link=LINK,
                    time=datetime.datetime.now()
                )
                user_message = UserMessage(
                    heading=TITLE,
                    message=CONTENT,
                    link_text=LINK_TEXT,
                    link=LINK,
                )
                user_message.message_type = UserMessageType.objects.get(name="sms")
                user_message.save()
                user_message.users.add(province_operator_user)
                item.user_message = user_message
                item.province_state_modal = False
                item.province_state_sms = True
                item.province_state = True
                item.main_check = "province_end"
                item.save()


def send_request_notification_to_poultry_from_killhouse():
    pass


class Command(BaseCommand):
    help = 'Closes the specified poll for voting'

    def add_arguments(self, parser):
        pass

    def handle(self, *args, **options):
        # schedule.every(2).hours.do()
        # schedule.every(5).hours.do()
        # schedule.every(10).minutes.do(job)
        # schedule.every().hour.do(job)
        # schedule.every().day.at("10:30").do(job)
        # schedule.every().monday.do(job)
        # schedule.every().wednesday.at("13:15").do(job)
        while (True):
            schedule.every(1).minutes.do(Check_Poultry_Auction_request)
            schedule.run_pending()
            print("function run !!!")
