# -*- encoding: UTF8 -*-
# Test harness for CheckJobEditTrigger.py

from __future__ import print_function

import sys
import unittest
import os
import re

import P4
from p4testutils import TestCase, P4Server

parent_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, parent_dir)
from CheckJobEditTrigger import CheckJobEditTrigger, REPLICATOR_USER

os.environ["LOGS"] = "."
LOGGER_NAME = "TestCheckJobEditTrigger"
LOG_FILE = "log-TestCheckJobEditTrigger.log"

python3 = sys.version_info[0] >= 3


class TestCheckJobEditTrigger(TestCase):
    def __init__(self, methodName='runTest'):
        super(TestCheckJobEditTrigger, self).__init__(LOGGER_NAME, LOG_FILE, methodName=methodName)

    def setUp(self):
        pass

    def tearDown(self):
        pass

    def testCheckJobEditTrigger(self):
        """ordinary jobs command is OK"""
        self.server = P4Server()
        trigpath = os.path.join(parent_dir, "CheckJobEditTrigger.py")
        p4 = self.server.p4
        p4.logger = self.logger
        # This works if no spaces in server root pathname!
        port = p4.port.replace('"', '')
        self.logger.debug("port: |%s|" % port)
        triggers = p4.fetch_triggers()
        triggers['Triggers'] = ['check_job_edit form-in job " python {} -r -p %quote%{}%quote% -u {} '
                                '%user% %formfile% "'.format(trigpath, port, p4.user)]
        self.logger.debug(triggers)
        p4.save_triggers(triggers)
        # Reconnect to pick up changes
        p4.disconnect()
        p4.connect()

        # Replicator user allowed to create jobs
        testuser = p4.user
        p4.user = REPLICATOR_USER
        job = p4.fetch_job()
        job['Description'] = "Description1"
        result = p4.save_job(job)
        self.logger.debug(result)
        jobname = self.get_jobname(result)

        # Ordinary user not allowed to create jobs
        p4.user = testuser
        try:
            job = p4.fetch_job()
            job['Description'] = "Description2"
            p4.save_job(job)
            self.assertTrue(False, "Expected exception not found")
        except P4.P4Exception as e:
            self.assertRegex(str(e), "You are not allowed to create new jobs")


        try:
            job = p4.fetch_job("newjob")
            job['Description'] = "Description2"
            p4.save_job(job)
            self.assertTrue(False, "Expected exception not found")
        except P4.P4Exception as e:
            self.assertRegex(str(e), "You are not allowed to create new jobs")


        # Ordinary user can't change readonly fields
        try:
            job = p4.fetch_job(jobname)
            job['Description'] = "Description2"
            p4.save_job(job)
            self.assertTrue(False, "Expected exception not found")
        except P4.P4Exception as e:
            self.assertRegex(str(e), r"You have changed one or more read.*only job fields")

        # Ordinary user can change writeable fields
        job = p4.fetch_job(jobname)
        job['Status'] = "suspended"
        result = p4.save_job(job)
        self.logger.debug(result)
        self.assertRegex(result[0], "Job .* saved")


    def testJobRename(self):
        """jobs are renamed for p4dtg"""
        self.server = P4Server()
        trigpath = os.path.join(parent_dir, "CheckJobEditTrigger.py")
        p4 = self.server.p4
        p4.logger = self.logger
        # This works if no spaces in server root pathname!
        port = p4.port.replace('"', '')
        self.logger.debug("port: |%s|" % port)
        triggers = p4.fetch_triggers()
        triggers['Triggers'] = ['check_job_edit form-in job " python {} -r -p %quote%{}%quote% -u {} '
                                '%user% %formfile% "'.format(trigpath, port, p4.user)]
        self.logger.debug(triggers)
        p4.save_triggers(triggers)
        # Reconnect to pick up changes
        p4.disconnect()
        p4.connect()

        # Setup up jobspec to approximate P4DTG
        job_spec = p4.fetch_jobspec()
        job_spec['Fields'].append("106 P4DTG_DTISSUE word 32 optional")
        self.logger.debug(job_spec)
        p4.save_jobspec(job_spec)
        # Reconnect to pick up changes
        p4.disconnect()
        p4.connect()

        # Replicator user allowed to create jobs
        testuser = p4.user
        p4.user = REPLICATOR_USER

        # Now job is renamed - but not when field not set

        job = p4.fetch_job()
        job['Description'] = "Description2"
        job['P4DTG_DTISSUE'] = 'PROJ-1'
        result = p4.save_job(job)
        self.logger.debug("Job save: %s" % str(result))
        jobname = self.get_jobname(result)
        self.assertEqual("PROJ-1", jobname)

        p4.user = testuser
        # Ordinary user can't change readonly fields
        try:
            job = p4.fetch_job(jobname)
            job['Description'] += "new"
            p4.save_job(job)
            self.assertTrue(False, "Expected exception not found")
        except P4.P4Exception as e:
            self.assertRegex(str(e), r"You have changed one or more read.*only job fields")

        # Ordinary user can change writeable fields
        job = p4.fetch_job(jobname)
        job['Status'] = "suspended"
        result = p4.save_job(job)
        self.logger.debug(result)
        self.assertRegex(result[0], "Job .* saved")


    def testJobRenamePrefix(self):
        """jobs are renamed with a prefix for p4dtg"""
        self.server = P4Server()
        trigpath = os.path.join(parent_dir, "CheckJobEditTrigger.py")
        p4 = self.server.p4
        p4.logger = self.logger
        # This works if no spaces in server root pathname!
        port = p4.port.replace('"', '')
        self.logger.debug("port: |%s|" % port)
        triggers = p4.fetch_triggers()
        triggers['Triggers'] = ['check_job_edit form-in job " python {} -r --prefix P4- -p %quote%{}%quote% -u {}'
                               ' %user% %formfile% "'.format(trigpath, port, p4.user)]
        self.logger.debug(triggers)
        p4.save_triggers(triggers)
        # Reconnect to pick up changes
        p4.disconnect()
        p4.connect()

        # Setup up jobspec to approximate P4DTG
        job_spec = p4.fetch_jobspec()
        job_spec['Fields'].append("106 P4DTG_DTISSUE word 32 optional")
        self.logger.debug(job_spec)
        p4.save_jobspec(job_spec)
        # Reconnect to pick up changes
        p4.disconnect()
        p4.connect()

        # Replicator user allowed to create jobs
        testuser = p4.user
        p4.user = REPLICATOR_USER

        # Now job is renamed - but not when field not set

        job = p4.fetch_job()
        job['Description'] = "Description2"
        job['P4DTG_DTISSUE'] = 'PROJ-1'
        result = p4.save_job(job)
        self.logger.debug("Job save: %s" % str(result))
        jobname = self.get_jobname(result)
        self.assertEqual("P4-PROJ-1", jobname)

        p4.user = testuser
        # Ordinary user can't change readonly fields
        try:
            job = p4.fetch_job(jobname)
            job['Description'] += "new"
            p4.save_job(job)
            self.assertTrue(False, "Expected exception not found")
        except P4.P4Exception as e:
            self.assertRegex(str(e), r"You have changed one or more read.*only job fields")

        # Ordinary user can change writeable fields
        job = p4.fetch_job(jobname)
        job['Status'] = "suspended"
        result = p4.save_job(job)
        self.logger.debug(result)
        self.assertRegex(result[0], "Job .* saved")

    def get_jobname(self, result):
        m = re.search("Job ([^ ]+) saved", result[0])
        self.assertTrue(m)
        jobname = m.group(1)
        return jobname


if __name__ == '__main__':
    unittest.main()
