from datetime import datetime
from .models import SHIFTS
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger


def paginate(request, query, page_number):
    page = request.GET.get('page', 1)
    paginator = Paginator(query, int(page_number))
    try:
        data = paginator.page(page)
    except PageNotAnInteger:
        data = paginator.page(1)
    except EmptyPage:
        data = paginator.page(paginator.num_pages)

    return data


def set_case_code(line, date, hour):
    datetime_object = datetime.strptime(date, '%Y-%m-%d')
    case_code = f"{line}{date.split('-')[0][2:]}{datetime.strftime(datetime_object, '%j')}{hour}"
    return case_code

    #2023-02-15


def set_shift_analysis_table(shift, analysis_data, fault_data, product_type):
    analysis = []
    available_hours = []
    for m in SHIFTS[shift]:
        if len(list(filter(lambda p: p['hour'] == m, analysis_data))) > 0:
            h = list(filter(lambda p: p['hour'] == m, analysis_data))[0]
            #h = analysis_data.filter(hour=m).first()
            if product_type == "ALCOHOLIC":
                analysis.append({'id':h['id'], 'hour':m, 'fault':None, 'minor': h['label_defect'], 'major':int(h['cap_defect'])+int(h['bottle_defect']), 'critical':h['clarity']})
            elif product_type == "NON-ALCOHOLIC":
                analysis.append({'id':h['id'],'hour':m, 'fault':None, 'minor': h['label_defect'], 'major':int(h['corking_caping_defect'])+int(h['bottle_defect']), 'critical':h['clarity']})

        elif len(list(filter(lambda p: p['hour'] == m, fault_data))) > 0:
            h = list(filter(lambda p: p['hour'] == m, fault_data))[0]
            analysis.append({'id':h['id'], 'hour':m, 'fault':h['fault'], 'minor': None, 'major':None, 'critical':None})

        else:
            available_hours.append(m)

    return (analysis, available_hours)


def set_shift_inspection_table(shift, analysis_data, fault_data, product_type):
    analysis = []
    available_hours = []
    for m in SHIFTS[shift]:
        if len(list(filter(lambda p: p['hour'] == m, analysis_data))) > 0:
            h = list(filter(lambda p: p['hour'] == m, analysis_data))[0]
            #h = analysis_data.filter(hour=m).first()
            if product_type == "ALCOHOLIC":
                analysis.append({'id':h['id'], 'hour':m, 'fault':None, 'minor': int(h['label_defect']) + int(h['shrink_wrapping_defect']), 'major':int(h['cap_defect'])+int(h['bottle_defect']), 'critical':h['clarity']})
            elif product_type == "NON-ALCOHOLIC":
                analysis.append({'id':h['id'],'hour':m, 'fault':None, 'minor': int(h['label_defect'])+int(h['foil_defect']), 'major':int(h['cork_cap_defect'])+int(h['bottle_defect'])+int(h['wire_hooding_defect']), 'critical':h['clarity']})

        elif len(list(filter(lambda p: p['hour'] == m, fault_data))) > 0:
            h = list(filter(lambda p: p['hour'] == m, fault_data))[0]
            analysis.append({'id':h['id'], 'hour':m, 'fault':h['fault'], 'minor': None, 'major':None, 'critical':None})

        else:
            available_hours.append(m)

    return (analysis, available_hours)


def set_sachet_shift_analysis_table(shift, analysis_data, fault_data, defect_data):
    analysis = []
    available_hours = []
    for m in SHIFTS[shift]:
        if len(list(filter(lambda p: p['hour'] == m, analysis_data))) > 0:
            h = list(filter(lambda p: p['hour'] == m, analysis_data))[0]
            analys = {'id':h['id'], 'hour':m, 'fault':None, 'weight': h['weight'], 'clarity':h['clarity']}
            analys['minor'] = 0
            analys['major'] = 0
            analys['critical'] = 0

            if len(list(filter(lambda d : d.hour == m, defect_data))) > 0:  
                for dft in list(filter(lambda d : d.hour == m, defect_data)):
                    try:
                        if dft.defect_id.defect_category == 'MINOR':
                            analys['minor'] += 1
                        elif dft.defect_id.defect_category == 'MAJOR':
                            analys['major'] += 1
                        elif dft.defect_id.defect_category == 'CRITICAL':
                            analys['critical'] += 1
                    except:
                        pass

            analysis.append(analys)
           
        elif len(list(filter(lambda p: p['hour'] == m, fault_data))) > 0:
            h = list(filter(lambda p: p['hour'] == m, fault_data))[0]
            analysis.append({'id':h['id'], 'hour':m, 'fault':h['fault'], 'weight': None, 'clarity': '--',  'minor': '--', 'major': '--', 'critical': '--'})

        else:
            available_hours.append(m)

    return (analysis, available_hours)


def set_sachet_shift_inspection_table(shift, analysis_data, fault_data, defect_data):
    analysis = []
    available_hours = []
    for m in SHIFTS[shift]:
        if len(list(filter(lambda p: p['hour'] == m, analysis_data))) > 0:
            h = list(filter(lambda p: p['hour'] == m, analysis_data))[0]
            analys = {'id':h['id'], 'hour':m, 'fault':None, 'weight': h['weight']}
            analys['minor'] = 0
            analys['major'] = 0
            analys['critical'] = 0

            if len(list(filter(lambda d : d.hour == m, defect_data))) > 0:  
                for dft in list(filter(lambda d : d.hour == m, defect_data)):
                    try:
                        if dft.defect_id.defect_category == 'MINOR':
                            analys['minor'] += 1
                        elif dft.defect_id.defect_category == 'MAJOR':
                            analys['major'] += 1
                        elif dft.defect_id.defect_category == 'CRITICAL':
                            analys['critical'] += 1
                    except:
                        pass

            analysis.append(analys)
           
        elif len(list(filter(lambda p: p['hour'] == m, fault_data))) > 0:
            h = list(filter(lambda p: p['hour'] == m, fault_data))[0]
            analysis.append({'id':h['id'], 'hour':m, 'fault':h['fault'], 'weight': None, 'minor': '--', 'major': '--', 'critical': '--'})

        else:
            available_hours.append(m)

    return (analysis, available_hours)




""" CONVERT LIST TO STRING FOR JS """
def list_to_string_conv(list_set):
    return ',,'.join(list_set)




#'CREATED', 'ANALYSED', 'CHECKED', 'APPROVED'
""" FOR CREATED """
""" ONLY INITIATOR SUPERVISOR CAN UPDATE/DELETE """
""" ONLY SUPERVISOR CAN UPDATE/DELETE """


""" FOR ANALYSED """
""" ONLY INITIATOR SHIFT HEAD CAN UPDATE/DELETE """
""" ONLY SHIFT HEAD CAN UPDATE/DELETE """


""" FOR CHECKED """
""" ONLY CHECKER CAN UPDATE/DELETE """

""" FOR APPROVED """
""" CANNOT BE UPDATED / DELETED """

##ARGS = STATUS, CREATOR, ANALYSER, CHECKER, APPROVER

def actions_validator(request, status, workflow, has_dependency=True):
    
    actions = {'can_update':False, 'can_delete':False, 'can_add_dep':False, 'can_delete_dep':False}

    if status == 'CREATED':
        actions = {'can_update':True, 'can_delete':True, 'can_add_dep':True, 'can_delete_dep':True}
    
    elif status == 'ANALYSED':
        if workflow['analysed_by'] == request.user.username or request.user.profile.role == 'SUPERADMIN':
            actions = {'can_update':True, 'can_delete':True, 'can_add_dep':True, 'can_delete_dep':True}

    elif status == 'CHECKED':
        if workflow['checked_by'] == request.user.username or request.user.profile.role == 'SUPERADMIN':
            actions = {'can_update':True, 'can_delete':True, 'can_add_dep':True, 'can_delete_dep':True}

    if has_dependency:
        actions['can_delete'] = False

    return actions



def form_set_shift_analysis_table(shift, analysis_data, fault_data):
    
    analysis = {}
    for m in SHIFTS[shift]:
        if analysis_data.filter(hour=m).count() > 0:
            analysis[m] = list(analysis_data.filter(hour=m).values())[0]
            analysis[m]['activity'] = 'BOTTLING'
        elif fault_data.filter(hour=m).count() > 0:
            analysis[m] = list(fault_data.filter(hour=m).values())[0]
            analysis[m]['activity'] = 'FAULT'
        else:
            analysis[m] = {'activity':'NONE'}

    return analysis