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

from __future__ import print_function

import sys
import unittest
import os

from p4testutils import TestCase, P4Server

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

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


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

    def setUp(self):
        pass

    def tearDown(self):
        pass


    def setupServer(self, config_path):
        self.server = P4Server()
        trig_path = os.path.join(parent_dir, "DefaultSwarmReviewDesc.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'] = ['default-swarm-desc form-in change "python {} -c {}'
                                ' -p %quote%{}%quote% -u {} %user% %formfile%"'.format(
            trig_path, config_path, port, p4.user)]
        self.logger.debug(triggers)
        p4.save_triggers(triggers)
        # Reconnect to pick up changes
        p4.disconnect()
        p4.connect()
        return p4

    def testChangeDesc(self):
        """jobs are renamed for p4dtg"""
        config_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "~test_config.yaml")
        p4 = self.setupServer(config_path)

        with open(config_path, "w") as f:
            f.write("""
swarm_user: swarm
review_description:
  - "Please review me!"
  - "Don't forget to check YYYY"
""")

        chg = p4.fetch_change()
        chg["Description"] = "My change description"
        p4.save_change(chg)

        # Make sure that the trigger doesn't fire again - so what is put in above survives
        chg = p4.fetch_change("1")
        self.assertRegex(chg["Description"], "My change description")

        # Now process as user defined in config file
        p4.user = "swarm"

        chg = p4.fetch_change()
        chg["Description"] = "Change desc 2"
        p4.save_change(chg)

        # Test that the template is updated from config file
        chg = p4.fetch_change("2")
        self.assertRegex(chg["Description"], "Please review me!")
        chg["Description"] = "New change desc"
        p4.save_change(chg)

        # Make sure that the trigger doesn't fire again - so what is put in above survives
        chg = p4.fetch_change("2")
        self.assertRegex(chg["Description"], "New change desc")


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