# -*- Mode: perl; indent-tabs-mode: nil -*-
#
# The contents of this file are subject to the Mozilla Public
# License Version 1.1 (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.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS
# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
# implied. See the License for the specific language governing
# rights and limitations under the License.
#
# The Original Code is the FlagUpdate Bugzilla Extension.
#
# The Initial Developer of the Original Code is YOUR NAME
# Portions created by the Initial Developer are Copyright (C) 2012 the
# Initial Developer. All Rights Reserved.
#
# Contributor(s):
#   Nagalenoj <nagalenoj@gmail.com>

package Bugzilla::Extension::FlagUpdate;
use strict;
use base qw(Bugzilla::Extension);

use Bugzilla::Error;
use Bugzilla::Flag;
use Data::Dumper;

our $VERSION = '1.0';
use constant NAME => 'FlagUpdate';

# -- Configuration -----------------------------------------------------------
# Sample:
# use constant FLAG_TRIGGERS => {
# 	'resolution' => {
# 		<RESOLUTION> => <FLAG_ID>,
# 		<RESOLUTION> => <FLAG_ID>,
# 	},
# 	'bug_status' => {
# 		<BUG_STATUS> => <FLAG_ID>,
# 	}
# };
# FLAG_ID -> is the ID you see in URL when editing the flag.
#
use constant FLAG_TRIGGERS => {
	'resolution' => {
	},
	'bug_status' => {
	}
};
# ----------------------------------------------------------------------------

# Hook function which gets called when a bug gets updated.
sub bug_end_of_update {
	my ($self, $args) = @_;
	my ($changes, $bug) = @$args{qw/changes bug/};

	return unless
		scalar keys %$changes &&
		exists $changes->{'resolution'} ||
		exists $changes->{'bug_status'};
	
	my @flags = $self->_select_flags($changes);
	return unless @flags;

	# Set the flags to '?'.
	foreach (@flags) {
		Bugzilla::Flag->set_flag(
			$bug,
			{
				type_id   => $_,
				status    => "?",             
			}
		); 
		$bug->update;
	}
}

# Function to select the list of flags to be updated for the changes made in status/resolution.
sub _select_flags {
	my ($self, $changes) = @_;
	my @flags_to_update;

	my $conf = $self->FLAG_TRIGGERS;

	foreach ('bug_status', 'resolution') {
		# Check whether changes made bug_status or resolution.
		if (exists $changes->{$_}) {
			my $state = $changes->{$_}->[1];

			# Check whether changed state(status/resolution) is configured to update a flag. 
			if (exists $conf->{$_}->{$state}) {
				push @flags_to_update, $conf->{$_}->{$state};
			}
		}
	}
	return unless @flags_to_update;

	# Remove duplicates
	my %flags;
	$flags{$_} = 1 foreach @flags_to_update;

	return keys %flags;
}

__PACKAGE__->NAME;
