# encoding: utf-8
# Copyright 2013 maker
# License

"""
    Infrastructure module views
"""
from django.shortcuts import get_object_or_404
from django.template import RequestContext
from maker.core.rendering import render_to_response
from maker.infrastructure.models import Item, ItemField, ItemType, ItemStatus, ItemServicing
from maker.infrastructure.forms import ItemForm, ItemTypeForm, ItemStatusForm, FilterForm, \
                                          MassActionForm, ItemFieldForm, ServiceRecordForm, SettingsForm
from maker.core.forms import LocationForm
from maker.core.models import Object, ModuleSetting, Location
from maker.core.views import user_denied
from maker.core.decorators import maker_login_required, handle_response_format, module_admin_required
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.db.models import Q

def _get_filter_query(args, model=Item):
    "Creates a query to filter Items based on FilterForm arguments"
    query = Q()
    
    for arg in args:
        if hasattr(model, arg) and args[arg]:
            kwargs = {str(arg + '__id'): long(args[arg])}
            query = query & Q(**kwargs)
    
    return query

def _get_default_context(request):
    "Returns default context for all views as dict()"
    
    types = Object.filter_by_request(request, ItemType.objects.filter(parent__isnull=True))
    statuses = Object.filter_by_request(request, ItemStatus.objects)
    locations = Object.filter_by_request(request, Location.objects)
    massform = MassActionForm(request.user.get_profile())
        
    context = {
               'statuses': statuses,
               'types': types,
               'massform': massform,
               'locations': locations
               }
    
    return context

def _process_mass_form(f):
    "Pre-process request to handle mass action form for Tasks and Milestones"
        
    def wrap(request, *args, **kwargs):
        "Wrap"
        if 'massform' in request.POST:
            for key in request.POST: