from itertools import product, combinations
from django.conf import settings

from django.db import transaction
from rest_framework import serializers, status
from api.models import TtUsagePreference, TtStartPreference, TtSetting, TtPos, TtPosModuleGroupModule, TtPathway, \
    TtPathwayPosModuleGroupModule, TtPosModuleGroup, TtActivity, UserSchedulingPreference, UserConstraintSetting
from api.models.audit_trail import AuditTrail
from api.models.audit_trail_details import AuditTrailDetails
from api.views.admin.base import AdminApiBase
from api.validator import BaseValidator
from api.utils import decrypt_aes_128_cbc, encrypt_aes_128_cbc, log_critical_error, get_exception_detail, \
    get_add_new_data, get_ip, bulk_sync_to_redis, push_websocket_notification, calculate_slot_by_start_time_slot, \
    calculate_slot_by_day, get_slot_default_pattern
from rest_framework.exceptions import ValidationError
from api.translation import __
from backend.kafka import send_request
from backend.redis_client import redis_client


class PrescheduleRequest(AdminApiBase):
    def validate_request(self,request):
        rules = {
            "activity_ids": "required|array|exists:api.TtActivity,id",
            "socket_id": "nullable",
            "constraint_breaking_mode": "nullable",
        }

        # if need rename field, can put here
        attribute = {
            # "email": __("attr.email"),
        }

        validator = BaseValidator(request.data,rules,attribute)
        error = validator.validate()
        if error:
            raise ValidationError(error)

        # custom error after basic validation

    def post(self, request):
        # Validate input
        try:
            self.validate_request(request)
            setting_params = {
                "slot_per_week",
                "slot_per_day"
            }
            user = request.user

            settings = TtSetting.get_multiple_setting(setting_params)
            slot_per_week = int(settings["slot_per_week"])
            slot_per_day = int(settings["slot_per_day"])
            activity_ids = request.data["activity_ids"]
            # action = "preschedule_request"
            method = "preschedule"
            activities = TtActivity.objects.filter(id__in=activity_ids).select_related("week_pattern").prefetch_related("week","week_pattern__week")

            kafka_topic = self.kafka_config['REQUEST_TOPIC']
            # kafka_topic = "test-topic"
            constraint_breaking_mode = 1 if request.data.get("constraint_breaking_mode") == 1 else 0
            # constraint setting
            user_constraint_setting_list = UserConstraintSetting.get_setting(user.id)
            # scheduling preference
            user_scheduling_preference_list = UserSchedulingPreference.get_setting(user.id)

            kafka_request_data = {
                "session_id": request.user.name,
                "activities": [],
                "slot": None, # force to put a None, cause schedule machine there required
                "constraint_breaking_mode": constraint_breaking_mode,
                "constraint_setting": UserConstraintSetting.kafka_group_settings_data(user_constraint_setting_list),
                "scheduling_preference": UserSchedulingPreference.kafka_group_settings_data(user_scheduling_preference_list),
            }
            for activity_id in activity_ids:
                kafka_request_data["activities"].append(activity_id)
            #
            # test_request={
            #     "session_id": "dev",
            #     "status": "success",
            #     "schedule": "[{\"activity\":\"190\",\"teaching_staff\":\"[47,48]\",\"start_slot\":\"400\",\"location\":\"[23,24]\"},{\"activity\":\"191\",\"teaching_staff\":\"[47,48]\",\"start_slot\":\"410\",\"location\":\"[23,24]\"}]"
            # }
            # temporary constraint break is manual handle first
            # if len(activity_ids) == 1 and activities and constraint_breaking_mode:
            #     manual_constraint_break(activities.first(),request.data.get("socket_id"),slot_per_week,slot_per_day)
            # else:
            #     send_request(kafka_topic, kafka_request_data, request.data.get("socket_id"),method)
            send_request(kafka_topic, kafka_request_data, request.data.get("socket_id"),method)

            # insert audit trail and details
            # can insert the parent first, then only insert details
            name = ",".join(activities.values_list("name", flat=True))

            # audit_trail = AuditTrail.objects.create(
            #     user_id=request.user.id,
            #     type=self.audit_type,
            #     ip_address=get_ip(request)
            # )
            # remark_param = {
            #     "name":name,
            # }

            # Listing no need to insert audit trail
            # call to a function for insert details, so in future if want change to used worker, can modify in function only
            # AuditTrailDetails.custom_insert(
            #     audit_trail=audit_trail,
            #     action=action,
            #     remark_param=remark_param,
            #     # new_data="",
            # )
            response = {

            }

            return self.api_response(data=response)
        except ValidationError as e:
            first_message = e.detail['error']
            errors = e.detail['errors']
            return self.api_response(error=first_message,errors=errors,code=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            e_details = get_exception_detail(e)
            log_critical_error(user_id=None,descr=e_details['descr'],url=e_details['url'],trace=e_details['trace'])
            return self.api_response(error=__("message.internal_server_error"),code=status.HTTP_500_INTERNAL_SERVER_ERROR)

def manual_constraint_break(activity,socket_id,slot_per_week,slot_per_day):
    """
    temporary function be4 engine complete constraint break
    only allow 1 activity
    """
    websocket_host = settings.WEBSOCKET_CONFIG["HOST"]
    websocket_port = str(settings.WEBSOCKET_CONFIG["PORT"])
    websocket_preschedule_endpoint = str(settings.WEBSOCKET_CONFIG["PRESCHEDULE_RESPONSE_ENDPOINT"])
    websocket_preschedule_url = websocket_host + ":" + websocket_port + "/" + websocket_preschedule_endpoint
    default_pattern = get_slot_default_pattern(slot_per_week)
    slot_required = activity.slot_required
    # all is available first
    pattern = default_pattern["availability"]
    # constraint break wont ignore suggested_day and suggested time
    if activity.suggested_time_slot is not None:
        time_pattern = calculate_slot_by_start_time_slot(activity.suggested_time_slot, activity.slot_required,slot_per_week, slot_per_day)
        pattern = "".join([max(a, b) for a, b in zip(pattern, time_pattern)])

    if activity.suggested_day is not None:
        day_pattern = calculate_slot_by_day([activity.suggested_day], slot_per_week, slot_per_day)
        pattern = "".join([max(a, b) for a, b in zip(pattern, day_pattern)])

    total_slot = len(pattern)
    # having an all 1 pattern list, at the end will return this to FE
    result_pattern_list = [1] * total_slot
    # loop 0 till total slot + 1, if not + 1, will miss last slot checking
    for i in range(total_slot - slot_required + 1):
        # based on previous calculated pattern value, if that position is 0, will having this checking
        if pattern[i] == "0":
            # if i is 5 and slot_required is 4, affected slot will be pattern[5:9], so the result will get position 5,6,7,8 data, wont get till position 9
            affected_slot = pattern[i: i + slot_required]
            if "1" not in affected_slot:
                # if affected slot all is 0, means this position "i" is available to schedule, so will update result pattern list to 0
                result_pattern_list[i] = 0

    wek_socket_data = {
        "activity": activity.id,
        "preference": [],
        "status": [],
    }
    for val in result_pattern_list:
        preference = 0
        if val == 0:
            preference = 9
        wek_socket_data["preference"].append(preference)
        if preference == 9:
            wek_socket_data["status"].append([])
        else:
            wek_socket_data["status"].append(["6"])
    if socket_id:
        # data will need have an array cover is the data only same as engine
        push_websocket_notification(websocket_preschedule_url, [wek_socket_data], socket_id)