# -*- coding: utf-8 -*-
#   Copyright 2007-2008 Agile42 GmbH - Andrea Tomasini 
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.
# 
# Authors:
#     - Andrea Tomasini <andrea.tomasini__at__agile42.com>

from agilo.api.view import JSONView
from agilo.scrum.backlog.controller import BacklogController
from agilo.ticket import LinksConfiguration
from agilo.utils import Key
from agilo.utils.config import AgiloConfig
from agilo.utils.web_ui import CoreTemplateProvider
from trac.util.translation import _

class BacklogMoveView(JSONView):
    """Class that represent the view to move tickets in the backlog using JSON
    commands"""
    url = '/json/backlogs'
    url_regex = '/(?P<name>[^/]+)(/(?P<scope>[^/]+))?/?$'
    
    def do_post(self, req, data):
        name = req.args.get(Key.NAME)
        scope = req.args.get(Key.SCOPE)
        # These should be in the JSON posted data.
        ticket = int(data.get(Key.TICKET))
        to_pos = int(data.get(Key.TO_POS))
        cmd_move = BacklogController.MoveBacklogItemCommand(self.env,
                                                            name=name,
                                                            scope=scope,
                                                            ticket=ticket,
                                                            to_pos=to_pos)
        return BacklogController(self.env).process_command(cmd_move)


class BacklogShowHideView(JSONView):
    """Class that represent the view to show and hide the tickets in the 
    backlog, this view only stores the hide and show information in the
    session so that when the page reloads, the tickets are keeping their
    status of hidden or shown"""
    url = '/json/tickets'
    url_regex = '/backlog/(?P<action>hide|show)/?$'
    
    def do_post(self, req, data):
        action = req.args.get(Key.ACTION)
        # Now get the json posted data
        my_tickets = bool(data.get(Key.MY_TICKETS) or False)
        closed_tickets = bool(data.get(Key.CLOSED_TICKETS) or False)
        if hasattr(req, 'session') and req.session is not None:
            if action == 'hide':
                if my_tickets:
                    req.session[Key.MY_TICKETS] = 1
                elif closed_tickets:
                    req.session[Key.CLOSED_TICKETS] = 0
            elif action == 'show':
                if my_tickets:
                    req.session[Key.MY_TICKETS] = 0
                elif closed_tickets:
                    req.session[Key.CLOSED_TICKETS] = 1
            # Now save the session explicitly because it is a JSON response and
            # the standard Trac request handler is ignored
            req.session.save()
        return {'stored': True}


class ConfiguredChildTypesView(JSONView):
    url = '/json/config/ticket/link'
    url_regex = ''
    
    def user_may_create(self, req, child_type):
        creation_permission = CoreTemplateProvider(self.env).get_permission_name_to_create
        action = creation_permission(child_type)
        return req.perm.has_permission(action)
    
    def possible_child_types_with_attributes_to_copy(self, parent_type):
        possible_types_with_attributes = []
        for allowed_link in LinksConfiguration(self.env).get_alloweds(parent_type):
            child_type = allowed_link._dest_type
            options_to_copy = allowed_link.get_option('copy')
            possible_types_with_attributes.append((child_type, options_to_copy))
        return possible_types_with_attributes
    
    def do_get(self, req, data):
        child_config = {}
        for parent_type in AgiloConfig(self.env).get_available_types(strict=True):
            child_config[parent_type] = {}
            for child_type, options_to_copy in self.possible_child_types_with_attributes_to_copy(parent_type):
                if not self.user_may_create(req, child_type):
                    continue
                child_config[parent_type][child_type] = options_to_copy
        return child_config

