from osinacore.models import *
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect 
from django.urls import reverse
from django.http import HttpResponse


@login_required
def edit_customer(request, customer_id):
    customer = get_object_or_404(CustomerProfile, customer_id=customer_id)

    #Utilities 
    references = Reference.objects.all()
    businesses = Business.objects.all
    customer_status = customer.status
    customer_reference = customer.reference
    customer_business = customer.business


    if request.method == 'POST':
         
        customer.user.first_name = request.POST.get('first_name')
        customer.user.last_name = request.POST.get('last_name')
        customer.user.email = request.POST.get('email')
        customer.user.save()
        customer.mobile_number = request.POST.get('mobile_number')
        customer.personal_website = request.POST.get('personal_website')
        customer.status = request.POST.get('status')

        customer_reference = request.POST.get('reference')
        reference = get_object_or_404(Reference, id=customer_reference)
        customer.reference = reference

        if customer.business:
            new_business = request.POST.get('business')
            business = get_object_or_404(Business, id=new_business)
            customer.business = business


        
        customer.save()
        

        return redirect('customerdetails', customer_id=customer.customer_id)    

    
    context = {

    'customer' : customer,
    'references' : references,
    'businesses' : businesses,
    'customer_status' : customer_status,
    'customer_reference' : customer_reference,
    'customer_business' : customer_business,

    }
    return render(request, 'edit_templates/edit-customer.html', context)




@login_required
def edit_business(request, business_id):
    business = get_object_or_404(Business, business_id=business_id)
    business_types = BusinessType.objects.all().order_by('name')
    current_business_type = None
    if business.type:
        current_business_type = business.type


    if request.method == 'POST':
         
        business.name= request.POST.get('name')
        business.financial_number = request.POST.get('financial_number')
        business.commercial_registration = request.POST.get('commercial_registration')
        business.vat = request.POST.get('vat')
        business.phone_number = request.POST.get('phone_number')
        business.website = request.POST.get('website')


        business_type = request.POST.get('business_type')
        type = get_object_or_404(BusinessType, id=business_type)
        business.type = type

        new_logo = request.FILES.get('logo')
        if new_logo:  
            business.logo = new_logo


        business.save()
        

        return redirect('businessdetails', business_id=business.business_id)      
    
    context = {
    'business' : business,
    'business_types' : business_types,
    'current_business_type' : current_business_type,

    }
    return render(request, 'edit_templates/edit-business.html', context)


@login_required
def edit_staff(request, staff_id):
    staff = get_object_or_404(StaffProfile, staff_id=staff_id)
    positions = StaffPosition.objects.all().order_by('name')
    current_position = staff.staff_position


    if request.method == 'POST':
         
        staff.user.first_name= request.POST.get('first_name')
        staff.user.last_name = request.POST.get('last_name')
        staff.user.email = request.POST.get('email')
        staff.user.save()

        staff.mobile_number = request.POST.get('mobile_number')
        staff.active = request.POST.get('active')
        staff.intern = request.POST.get('intern')

        new_position_id = request.POST.get('staff_position')
        new_position = get_object_or_404(StaffPosition, id=new_position_id)
        staff.staff_position = new_position


        new_image = request.FILES.get('image')
        if new_image:  
            staff.image = new_image

        staff.active = request.POST.get('active') == 'on'
        staff.intern = request.POST.get('intern') == 'on'


        staff.save()
        

        return redirect('userdetails', staff_id=staff.staff_id)    
    
    context = {
    'staff' : staff,
    'positions' : positions,
    'current_position' : current_position,

    }
    return render(request, 'edit_templates/edit-staff.html', context)



@login_required
def edit_project(request, project_id):
    project = get_object_or_404(Project, project_id=project_id)

    staffs = StaffProfile.objects.all().order_by('-id')
    current_manager = project.manager
    customers = CustomerProfile.objects.all().order_by('-id')
    current_client = project.customer 
    types = ProjectType.objects.all().order_by('-id')


    if request.method == 'POST':

        project.name = request.POST.get('name')

        new_customer_id = request.POST.get('customer')
        customer = get_object_or_404(CustomerProfile, id=new_customer_id)
        project.customer = customer

        new_manager_id = request.POST.get('manager')
        manager = get_object_or_404(StaffProfile, id=new_manager_id)
        project.manager = manager


        members_ids = request.POST.getlist('members')
        members_profiles = StaffProfile.objects.filter(id__in=members_ids)
        project.members.set(members_profiles)


        project.status = request.POST.get('status')


        type_ids = request.POST.getlist('types')
        types = ProjectType.objects.filter(id__in=type_ids)
        project.project_type.set(type_ids)


        project.details = request.POST.get('details')
        project.start_date = request.POST.get('start_date')
        project.end_date = request.POST.get('end_date')

        
        project.save()
        return redirect('detailed-project', project_id=project.project_id)    
        


    context = {

    'project' : project,
    'staffs' : staffs,
    'current_manager' : current_manager,
    'customers' : customers,
    'current_client' : current_client,
    'types' : types,


    }
    return render(request, 'edit_templates/edit-project.html', context)



@login_required
def edit_task(request, task_id):
    task = get_object_or_404(Task, task_id=task_id)
    projects = Project.objects.all().order_by('-id')
    staffs = StaffProfile.objects.all().order_by('-id')

    selected_project_id = request.POST.get('project', task.project.id) if request.method == 'POST' else task.project.id
    epics_of_my_project = Epic.objects.filter(project_id=selected_project_id)

    if request.method == 'POST':
        task.name = request.POST.get('name')
        
        project_id = request.POST.get('project')
        project = get_object_or_404(Project, id=project_id)
        task.project = project


        task.extra = request.POST.get('extra')


        epic_id = request.POST.get('epic')
        epic = get_object_or_404(Epic, id=epic_id)
        task.epic = epic
        
        task.requirement = request.POST.get('requirement')
        task.status = request.POST.get('status')

        # Convert assigned_to ID to a StaffProfile instance
        assigned_to_id = request.POST.get('assigned_to')
        assigned_to = get_object_or_404(StaffProfile, id=assigned_to_id)
        task.assigned_to = assigned_to
        
        task.description = request.POST.get('description')
        task.start_date = request.POST.get('start_date')
        task.end_date = request.POST.get('end_date')

        task.save()
        return redirect('detailed-task', task_id=task.task_id)

    context = {
        'task': task,
        'projects': projects,
        'epics_of_my_project': epics_of_my_project,
        'staffs': staffs,
    }
    return render(request, 'edit_templates/edit-task.html', context)




def edit_task_status_modal(request, *, task_id):
    task = get_object_or_404(Task, task_id=task_id)
    
    if request.method == 'POST':
        status = request.POST.get('status')
        task.status = status
        task.save()
    
        # Reload the parent page using JavaScript
        response = HttpResponse('<script>window.top.location.reload();</script>')
        return response

    context = {
        'task' : task,
    }
    
    return render(request, 'edit_templates/edit-taskstatus-modal.html', context)



@login_required
def edit_epic(request, *args, **kwargs):
    
    context = {

    }
    return render(request, 'edit_templates/edit-epic.html', context)
    


@login_required
def edit_project_type(request, projecttype_id):

 projecttype = get_object_or_404(ProjectType, id=projecttype_id)
    
 if request.method == 'POST':
     projecttype.name = request.POST.get('name')
     projecttype.save()

     return redirect('projecttypes')

 return render(request, 'edit_templates/edit-project-type.html', {'projecttype': projecttype})


@login_required
def edit_staff_position(request):

    context = {


    }
    return render(request, 'edit_templates/edit-staff-position.html', context)




@login_required
def edit_business_type(request, businesstype_id):

 businesstype = get_object_or_404(BusinessType, id=businesstype_id)
    
 if request.method == 'POST':
     businesstype.name = request.POST.get('name')
     businesstype.save()

     return redirect('businesstypes')

 return render(request, 'edit_templates/edit-business-type.html', {'businesstype': businesstype})


@login_required
def edit_reference(request, reference_id):
 reference = get_object_or_404(Reference, id=reference_id)
    
 if request.method == 'POST':
     reference.name = request.POST.get('name')
     reference.date = request.POST.get('date')
     reference.save()

     return redirect('references')

 return render(request, 'edit_templates/edit-reference.html', {'reference': reference})



@login_required
def edit_tag(request, tag_id):
 tag = get_object_or_404(Tag, id=tag_id)
    
 if request.method == 'POST':
     tag.name = request.POST.get('name')
     tag.save()

     return redirect('tags')

 return render(request, 'edit_templates/edit-tag.html', {'tag': tag})










#Mark points

@login_required
def mark_point_working_on(request, point_id, task_id):
    task = get_object_or_404(Task, id=task_id)
    point = get_object_or_404(Point, id=point_id)
    point.status = 'Working On'
    current_datetime = datetime.now()

    point.save()

    activity = PointActivity(
        point = point,
        start_time = datetime.now(),
    )
    activity.save()
   
    if PointActivity.objects.filter(point=point).count() == 1:
        status_text = f'Started Working On: {point.text}'
        status = Status(text=status_text, date=current_datetime.date(), time=current_datetime.strftime("%I:%M %p"), staff=request.user.staffprofile)
        status.save()
    else: 
        status_text = f'Resumed Working On: {point.text}'
        status = Status(text=status_text, date=current_datetime.date(), time=current_datetime.strftime("%I:%M %p"), staff=request.user.staffprofile)
        status.save()



    task_id_str = task.task_id

    showpoints_url = reverse('showpoints', args=[task_id_str])
    return HttpResponseRedirect(showpoints_url)



@login_required
def mark_point_working_on_task_page(request, point_id, task_id):
    task = get_object_or_404(Task, id=task_id)
    point = get_object_or_404(Point, id=point_id)
    point.status = 'Working On'
    current_datetime = datetime.now()

    point.save()

    activity = PointActivity(
        point = point,
        start_time = datetime.now(),
    )
    activity.save()
   
    if PointActivity.objects.filter(point=point).count() == 1:
        status_text = f'Started Working On: {point.text}'
        status = Status(text=status_text, date=current_datetime.date(), time=current_datetime.strftime("%I:%M %p"), staff=request.user.staffprofile)
        status.save()
    else: 
        status_text = f'Resumed Working On: {point.text}'
        status = Status(text=status_text, date=current_datetime.date(), time=current_datetime.strftime("%I:%M %p"), staff=request.user.staffprofile)
        status.save()

    
    return redirect('detailed-task', task_id=task.task_id)




@login_required
def mark_point_paused(request, point_id, task_id):
    task = get_object_or_404(Task, id=task_id)
    point = get_object_or_404(Point, id=point_id)
    point.status = 'Paused'
    current_datetime = datetime.now()

    point.save()

    last_activity = PointActivity.objects.filter(point=point).last()
    if last_activity:
        last_activity.end_time = timezone.make_aware(current_datetime, timezone.get_current_timezone())
        last_activity.save()
    
    status_text = f'{point.text} - Paused'
    status = Status(text=status_text, date=current_datetime.date(), time=current_datetime.strftime("%I:%M %p"), staff=request.user.staffprofile)
    status.save()


    task_id_str = task.task_id

    showpoints_url = reverse('showpoints', args=[task_id_str])
    return HttpResponseRedirect(showpoints_url)



@login_required
def mark_point_completed(request, point_id, task_id):
    task = get_object_or_404(Task, id=task_id)
    point = get_object_or_404(Point, id=point_id)
    point.status = 'Completed'

    current_datetime = datetime.now()

    point.save()

    # Update the end time of the last activity to the current time
    last_activity = PointActivity.objects.filter(point=point).last()
    if last_activity:
        last_activity.end_time = timezone.make_aware(current_datetime, timezone.get_current_timezone())
        last_activity.save()


    total_time_hours, total_time_minutes, total_time_seconds = point.total_activity_time()
    
    formatted_time = ""
    if total_time_hours > 0:
        formatted_time += f"{total_time_hours}{'hr' if total_time_hours == 1 else 'hrs'}"
    if total_time_minutes > 0:
        formatted_time += f" {total_time_minutes}{'min' if total_time_minutes == 1 else 'mins'}"
    if total_time_seconds > 0:
        formatted_time += f" {total_time_seconds}{'sec' if total_time_seconds == 1 else 'secs'}"

    status_text = f'{point.text} - Completed'
    if formatted_time:
        status_text += f' in {formatted_time}'

    status = Status(text=status_text, date=current_datetime.date(), time=current_datetime.strftime("%I:%M %p"), staff=request.user.staffprofile)
    status.save()

    task_id_str = task.task_id
    showpoints_url = reverse('showpoints', args=[task_id_str])
    return HttpResponseRedirect(showpoints_url)



@login_required
def mark_point_completed_task_page(request, point_id, task_id):
    task = get_object_or_404(Task, id=task_id)
    point = get_object_or_404(Point, id=point_id)
    point.status = 'Completed'
    current_datetime = datetime.now()


    point.save()

   
    last_activity = PointActivity.objects.filter(point=point).last()
    last_activity.end_time =  datetime.now()
    last_activity.save()


    status_text = f'{point.text} - Completed'
    status = Status(text=status_text, date=current_datetime.date(), time=current_datetime.strftime("%I:%M %p"), staff=request.user.staffprofile)
    status.save()

    return redirect('detailed-task', task_id=task.task_id)


