#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# ==============================================================================
# Copyright and license info is available in the LICENSE file included with
# the Server Deployment Package (SDP), and also available online:
# https://swarm.workshop.perforce.com/projects/perforce-software-sdp/view/main/LICENSE
# ------------------------------------------------------------------------------

# tag::includeManual[]
"""
NAME:
    SwarmReviewTemplate.py

DESCRIPTION:
    This trigger is intended for use with Swarm installations and other workflow triggers.

    It is intended to fire as a shelve-commit trigger which only fires for the swarm user.

    It updates the Review description with template text as appropriate.

    It will search for any jobs associated with the changelist and find any reviews
    associated with that job. If found it will update the review with this changelist

    To install, add a line to your Perforce triggers table like the following:

        swarm_template_review shelve-commit //... "python /p4/common/bin/triggers/SwarmReviewTemplate.py -c Workflow.yaml -p %serverport% -u perforce %change% "

    or (if server is standard SDP and has appropriate environment defaults for P4PORT and P4USER):

        swarm_template_review shelve-commit //... "python /p4/common/bin/triggers/SwarmReviewTemplate.py -c Workflow.yaml %change% "

    Note that -c/--config specifies a yaml file - see Workflow.yaml for example.

    You may need to provide the full path to python executable, or edit the path to the trigger.

    Also, don't forget to make the file executable.
"""
# end::includeManual[]

# Python 2.7/3.3 compatibility.
from __future__ import print_function

import sys

import WorkflowTriggers
import P4
import requests

class SwarmReviewTemplate(WorkflowTriggers.WorkflowTrigger):
    """See module doc string for details"""

    def __init__(self, *args, **kwargs):
        WorkflowTriggers.WorkflowTrigger.__init__(self, **kwargs)
        self.parse_args(__doc__, args)

    def add_parse_args(self, parser):
        """Specific args for this trigger - also calls super class to add common trigger args"""
        parser.add_argument('-c', '--config-file', default="/p4/common/config/Workflow.yaml",
                            help="Configuration file for trigger. Default: SwarmReviewTemplate.yaml")
        parser.add_argument('--test-mode', default=False, action='store_true',
                            help="Trigger runs in test mode - for unit testing only")
        parser.add_argument('change', help="Change to process - %%change%% argument from triggers entry.")
        super(SwarmReviewTemplate, self).add_parse_args(parser)

    def has_required_reviewers(self, review):
        """Parse json review description for required reviewers"""
        for part in review['participants'].keys():
            p = review['participants'][part]
            if 'required' in p and p['required']:
                return True
        return False
        
    def run(self):
        """Runs trigger"""
        try:
            self.logger.debug("SwarmReviewTemplate trigger firing")
            self.setupP4()
            self.p4.connect()
            change = self.getChange(self.options.change)

            config = self.load_config(self.options.config_file)
            if change.user != config['swarm_user']:
                self.logger.debug("Ignoring change as not swarm user")
                return 0

            if change.shelved and not change.files:
                try:
                    files = [x['depotFile'] for x in self.p4.run_files("@=%s" % self.options.change)]
                except:
                    self.logger.warning("Ignoring change as no files found for change %s" % self.options.change)
                    return 0
            else:
                files = [x.depotFile for x in change.files]

            # If we match the fix allowed paths then don't check further
            prj = self.get_project_by_files(config, files)
            self.logger.debug("Prj found: %s" % prj)
            if (not 'pre_submit_require_review' in prj or prj['pre_submit_require_review'] != 'y') and \
               (not 'swarm_review_template' in prj or prj['swarm_review_template'] != 'y'):
                self.logger.debug("Ignoring change as pre_submit_require_review not set")
                return 0

            swarm_url = self.get_swarm_url()
            base_url = "%s%s" % (swarm_url, config['api'])
            auth = (config['user'], config['ticket'])

            # If this change description is the same as the user's change then we process it, otherwise we assume
            # we have already run for this change.

            users_chg_id = ""
            url = '%s/reviews?ids[]=%s' % (base_url, self.options.change)
            self.logger.debug("Get: %s" % (url))
            resp = requests.get(url, auth=auth)
            resp_json = resp.json()
            self.logger.debug("Result: %s" % (resp_json))
            if 'reviews' in resp_json and resp_json['reviews']:
                review = resp_json['reviews'][0]
                changes = [str(c) for c in review['changes']]
                if len(changes) > 1:
                    self.logger.debug("Multiple changes found: %s" % (changes))
                if changes:
                    users_chg_id = changes[0]
                if self.has_required_reviewers(review):
                    # Reset requiredReviewers since otherwise Jenkins can't approve and commit
                    url = '%s/reviews/%s' % (base_url, self.options.change)
                    data = {'requiredReviewers': []}
                    resp = requests.patch(url, auth=auth, json=data)
                    self.logger.debug("Result: %s" % (resp.json()))

            if not users_chg_id:
                self.logger.debug("Ignoring review as no user change found")
                return 0

            try:
                users_chg = self.p4.fetch_change(users_chg_id)
            except:
                self.logger.debug("Failed to fetch change - assume description already modified")
                return 0
            if users_chg["Description"].rstrip("\n") != change.desc.rstrip("\n"):
                self.logger.debug("Ignoring review change as description already modified")
                return 0

            # Look for jobs attached to this changelist
            fixes = self.p4.run_fixes("-c", self.options.change)
            job_names = []
            jobs = []
            if fixes and len(fixes) > 0:
                for f in fixes:
                    if f['Job'] not in job_names:
                        job_names.append(f['Job'])
                for j in job_names:
                    jobs.append(self.p4.fetch_job(j))

            # Now update existing review and set description
            job_desc = ""
            change_desc = users_chg["Description"].rstrip("\n")
            if jobs and len(jobs) > 0:
                job_desc = jobs[0]['Description']
                job_desc = job_desc.rstrip("\n")
            description = self.formatReviewDescription(config['review_description'],
                                                       changeDescription=change_desc,
                                                       jobDescription=job_desc)
            # Now we update the description of the review
            url = '%s/reviews/%s' % (base_url, self.options.change)
            data = [('description', description)]
            self.logger.debug("Patch: %s data: %s" % (url, data))
            resp = requests.patch(url, auth=auth, data=data)
            self.logger.debug("Result: %s" % (resp.json()))
        except Exception:
            return self.reportException()

        return 0


if __name__ == '__main__':
    """ Main Program"""
    trigger = SwarmReviewTemplate(*sys.argv[1:])
    sys.exit(trigger.run())
