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



def add_status_modal(request, *args, **kwargs):
    if request.method == 'POST':
        text = request.POST.get('text')
        current_datetime = datetime.now()
        date = datetime.now().date()
        time = current_datetime.strftime("%I:%M %p") 

        try:
            staff_profile = StaffProfile.objects.get(user=request.user)
        except StaffProfile.DoesNotExist:
            # Handle the case where a StaffProfile does not exist for the user
            staff_profile = None

        status = Status(
            text=text,
            staff=staff_profile,
            date=date,
            time = time,
        )
        status.save()

        # Reload the parent page
        return HttpResponse('<script>window.top.location.reload();</script>')
    return render(request, 'add_templates/add-status-modal.html')



@login_required
def add_customer(request):
    businesses = Business.objects.all().order_by('-id')
    references = Reference.objects.all().order_by('-id')
    business_types = BusinessType.objects.all().order_by('-id')

    if request.method == 'POST':
        email = request.POST.get('email').lower()
        first_name = request.POST.get('first_name')
        last_name = request.POST.get('last_name')
        business_id = request.POST.get('business')
        business = get_object_or_404(Business, id=business_id)
        username = f"{first_name.lower()}{last_name.lower()}"
        original_username = username
        counter = 1 
            
        while User.objects.filter(username=username).exists():
            username = f"{original_username.lower()}{counter}"
            counter += 1
            
        user = User.objects.create_user(
            username=username,
            email=email,
            password=request.POST.get('password2')
        )
        user.first_name = first_name.lower().capitalize()
        user.last_name = last_name.lower().capitalize()
        user.save()
 

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

        CustomerProfile.objects.create(
            user=user,
            mobile_number = request.POST.get('mobile_number'),
            personal_website = request.POST.get('personal_website'),
            status = request.POST.get('status'),
            reference = reference,
            business = business,
        )
        return redirect('customers')

    context = {      
    'businesses' : businesses, 
    'references' :references,
    'business_types' : business_types

    }
    return render(request, 'add_templates/add-customer.html', context)
    


@login_required
def add_business(request):
    business_types = BusinessType.objects.all().order_by('-id')
    if request.method == 'POST':
        name = request.POST.get('name')
        email= request.POST.get('email')
        financial_number = request.POST.get('financial_number')
        phone_number = request.POST.get('phone_number')
        vat = request.POST.get('vat')
        if vat == 'true':
            vat = True
        else:
            vat = False
        commercial_registration = request.POST.get('commercial_registration')
        website = request.POST.get('website')
        logo = request.FILES.get('logo')

        business_type_id = request.POST.get('type')

        business_type = get_object_or_404(BusinessType, id=business_type_id)

        business = Business(
        name = name,
        email = email,
        financial_number = financial_number,
        vat = vat,
        commercial_registration = commercial_registration,
        website = website,
        type=business_type,
        logo = logo,
        phone_number = phone_number,
        )
        business.save()
    
        return redirect('businesses')

    context = {
        'business_types': business_types,
    }

    return render(request, 'add_templates/add-business.html', context)






@login_required
def add_business_modal(request):
    if request.method == 'POST':
        name = request.POST.get('name')
        email = request.POST.get('email')
        financial_number = request.POST.get('financial_number')
        phone_number = request.POST.get('phone_number')
        vat = request.POST.get('vat')
        if vat == 'true':
            vat = True
        else:
            vat = False
        commercial_registration = request.POST.get('commercial_registration')
        website = request.POST.get('website')
        logo = request.FILES.get('logo')

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

        business = Business(
            name=name,
            email=email,
            financial_number=financial_number,
            vat=vat,
            commercial_registration=commercial_registration,
            website=website,
            type=business_type,
            logo=logo,
            phone_number=phone_number,
        )
        business.save()

        
        businesses = Business.objects.all()

        updated_options = [{'id': business.id, 'name': business.name} for business in businesses]

        
        return JsonResponse(updated_options, safe=False)

    
    return render(request, 'add_templates/addbusiness-modal.html')


@login_required
def add_staff(request):
    staffpositions = StaffPosition.objects.all().order_by('-id')
    if request.method == 'POST':
        email = request.POST.get('email').lower()
        first_name = request.POST.get('first_name')
        last_name = request.POST.get('last_name')
        username = f"{first_name.lower()}{last_name.lower()}"
        original_username = username
        counter = 1 
            
        while User.objects.filter(username=username).exists():
            username = f"{original_username.lower()}{counter}"
            counter += 1

        user = User.objects.create_user(
            username=username,
            email=email,
            password= request.POST.get('password2')
        )
        user.first_name = first_name.lower().capitalize()
        user.last_name = last_name.lower().capitalize()
        user.save()

        staff_positionid = request.POST.get('staff_position')
        staff_position = get_object_or_404(StaffPosition, id=staff_positionid)

        StaffProfile.objects.create(
            user=user,
            image = request.FILES.get('image'),
            mobile_number = request.POST.get('mobile_number'),
            active = request.POST.get('active'),
            intern = request.POST.get('intern'),
            staff_position = staff_position,
            )
        return redirect('users')

    context = {
    'staffpositions' : staffpositions,
    }
    return render(request, 'add_templates/add-staff.html', context)



@login_required
def add_project(request):
    staffs = StaffProfile.objects.all().order_by('-id')
    project_types = ProjectType.objects.all()
    customers = CustomerProfile.objects.all().order_by('-id')
    if request.method == 'POST':
        name = request.POST.get('name')

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

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


        project_type = request.POST.getlist('project_type')
        details = request.POST.get('details')
        membersids = request.POST.getlist('members')
        status = request.POST.get('status')
        start_date = request.POST.get('start_date')
        end_date = request.POST.get('end_date') 


        project = Project(
            name=name,
            customer=customer,
            manager=manager,
            details=details,
            status=status,
            start_date=start_date,
            end_date=end_date,
        )
        project.save()
        
        project.project_type.set(project_type)
        project.members.set(membersids)

        requirements = request.POST.getlist('requirements') 
        for requirement_content in requirements:
            if requirement_content:
                requirement = ProjectRequirement(content=requirement_content, project=project, added_by=request.user)
                requirement.save()

        return redirect('my-projects')


    context = {       
    'staffs' : staffs,
    'project_types' : project_types,
    'customers' : customers,

    }
    return render(request, 'add_templates/add-project.html', context)


def add_user_story_modal(request, project_id):
    project = get_object_or_404(Project, project_id=project_id)
    if request.method == 'POST':
        content = request.POST.get('content')

        story = ProjectRequirement(
            content = content,
            project = project,
            added_by = request.user,
        )
        story.save()
        # Reload the parent page using JavaScript
        response = HttpResponse('<script>window.top.location.reload();</script>')
        return response

    
    context = {

        'project' : project,

    }

    return render(request, 'add_templates/add-userstory-modal.html', context)




def add_project_note_modal(request, project_id):
    project = get_object_or_404(Project, project_id=project_id)
    if request.method == 'POST':
        text = request.POST.get('note_text')
        color = request.POST.get('note_color')
        user = request.user
        date = timezone.now()

        note = Note(
            text=text,
            color=color,
            user=user,
            date=date,
            project=project,
        )
        note.save()

        return HttpResponse('<script>window.top.location.reload();</script>')

    context = {
        'project' : project
    }

    return render(request, 'add_templates/add-project-note-modal.html', context)   




def add_file_modal(request, *args, **kwargs):

    context = {

    }
    return render(request, 'add_templates/add-file-modal.html', context) 

def add_credential_modal(request, *args, **kwargs):
    context = {

    }
    return render(request, 'add_templates/add-credentials-modal.html', context) 




@login_required
def add_task(request, project_id=None, requirement_id=None):
    project = None
    requirement = None
    epics_of_my_project = None
    projects = None


    if project_id: #Case where user wants to add task from project page(Adding a task for a project)
        project = get_object_or_404(Project, project_id=project_id)
        epics_of_my_project = Epic.objects.filter(project=project)
        if requirement_id:
            requirement = get_object_or_404(ProjectRequirement, id=requirement_id)


    else:  #Case where user wants to add task from tasks page(No project specified)
        projects = Project.objects.all().order_by('-id')


    staffs = StaffProfile.objects.all().order_by('-id')


    if request.method == 'POST':
        name = request.POST.get('name')
        status = request.POST.get('status')
        extra = request.POST.get('extra') 
        description = request.POST.get('description')   
        start_date = request.POST.get('start_date')   
        end_date = request.POST.get('end_date')   



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

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


        assigned_to_id = request.POST.get('assigned_to')
        assigned_to = get_object_or_404(StaffProfile, id=assigned_to_id)

        task = Task(
            name=name,
            status=status,
            project=project, 
            epic=epic,
            extra=extra,
            description=description,
            start_date=start_date,
            end_date=end_date,
            assigned_to = assigned_to,
            requirement = requirement,

        )

        task.save()


        task_details_url = reverse('detailed-task', args=[task.task_id])
        if requirement:
         return redirect('detailed-project', project_id=project.project_id)
        else:
         return HttpResponseRedirect(task_details_url)
       

    context = {       
        'project':project,
        'epics_of_my_project' : epics_of_my_project,
        'staffs' : staffs,
        'projects' : projects,
        'requirement' : requirement


    }
    return render(request, 'add_templates/add-task.html', context)




def add_point_modal(request, task_id):
    task = get_object_or_404(Task, task_id=task_id)
    if request.method == 'POST':
        text = request.POST.get('text')
        point = Point(
        text = text,
        task = task,
        status='Not Completed'
        )
        point.save()

        # Redirect back to the same page
        return redirect(request.META.get('HTTP_REFERER', ''))
    
    context = {
        'task' : task,

    }
    return render(request, 'add_templates/add-point-modal.html', context)





@login_required
def add_epic(request, project_id):
    project = get_object_or_404(Project, project_id=project_id)
    if request.method == 'POST':
        title = request.POST.get('title')
        status = request.POST.get('status')
        description = request.POST.get('description')


        project_id = request.POST.get('project')
        project = get_object_or_404(Project, id=project_id)
 

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


        epic = Epic(
            title=title,
            status=status,
            project=project, 
            description=description,
            start_date=start_date,
            end_date=end_date
        )


        epic.save()

        redirect_url = reverse('detailed-project', args=[project.project_id])
        return redirect(redirect_url)
    
    context = {       
    'project' : project,
    }
    return render(request, 'add_templates/add-epic.html', context)




def add_note_modal(request, *args, **kwargs):
    if request.method == 'POST':
        text = request.POST.get('note_text')
        color = request.POST.get('note_color')
        user = request.user
        date = timezone.now()

        note = Note(
            text=text,
            color=color,
            user=user,
            date=date,
        )
        note.save()

        # Reload the parent page
        return HttpResponse('<script>window.top.location.reload();</script>')
    return render(request, 'add_templates/add-note-modal.html')



def add_daily_report(request):
    user = request.user
    today = date.today()
    statuses = Status.objects.filter(staff=user.staffprofile, date=today)
    if request.method == 'POST':
        text = request.POST.get('text')
        current_datetime = datetime.now()
        date = datetime.now().date()
        time = current_datetime.strftime("%I:%M %p") 
        try:
            staff_profile = StaffProfile.objects.get(user=request.user)
        except StaffProfile.DoesNotExist:
            # Handle the case where a StaffProfile does not exist for the user
            staff_profile = None       


        dailyreport = DailyReport(
        text = text,
        date = date,
        time = time,
        staff = staff_profile
        )
        dailyreport.save()
    
        
        return redirect('dailyreports')

    context = {
        'statuses': statuses,


    }
    return render(request, 'add_templates/add-daily-report.html', context)




def add_projecttype_modal(request, *args, **kwargs):
    if request.method == 'POST':
        name = request.POST.get('name')
        projecttype = ProjectType(
        name = name,
        
        )
        projecttype.save()

        # Reload the parent page
        return HttpResponse('<script>window.top.location.reload();</script>')
    return render(request, 'add_templates/add-projecttype-modal.html')



def add_staffposition_modal(request):
    if request.method == 'POST':
        name = request.POST.get('name')
        staffposition = StaffPosition(
        name = name,

        
        )
        staffposition.save()
    
        # Reload the parent page
        return HttpResponse('<script>window.top.location.reload();</script>')
    return render(request, 'add_templates/add-staffposition-modal.html')



def add_businesstype_modal(request, *args, **kwargs):
    if request.method == 'POST':
        name = request.POST.get('name')


        businesstype = BusinessType(
        name = name,
        )
        businesstype.save()


        # Reload the parent page
        return HttpResponse('<script>window.top.location.reload();</script>')
    
    return render(request, 'add_templates/add-businesstype-modal.html')





def add_reference_modal(request, *args, **kwargs):
    if request.method == 'POST':
        name = request.POST.get('name')
        date = request.POST.get('date')


        reference = Reference(
        name = name,
        date = date,
        )
        reference.save()


        # Reload the parent page
        return HttpResponse('<script>window.top.location.reload();</script>')
    return render(request, 'add_templates/add-reference-modal.html')




def add_tag_modal(request, *args, **kwargs):
    if request.method == 'POST':
        name = request.POST.get('name')
      

        tag = Tag(
        name = name,
        )
        tag.save()
    
        # Reload the parent page
        return HttpResponse('<script>window.top.location.reload();</script>')
    return render(request, 'add_templates/add-tag-modal.html')












