# Software License Agreement (BSD License)
#
# Copyright (c) 2009, Willow Garage, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
#  * Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
#  * Redistributions in binary form must reproduce the above
#    copyright notice, this list of conditions and the following
#    disclaimer in the documentation and/or other materials provided
#    with the distribution.
#  * Neither the name of Willow Garage, Inc. nor the names of its
#    contributors may be used to endorse or promote products derived
#    from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.

import datetime
import os
import sys
import subprocess

from test.io_wrapper import StringIO

from wstool.wstool_cli import wstool_main

from test.scm_test_base import AbstractSCMTest, _add_to_file, get_git_hash
from test.local.test_diff_functions_git import create_git_repo, modify_git_repo


class WstoolExportTest(AbstractSCMTest):

    @classmethod
    def setUpClass(self):
        AbstractSCMTest.setUpClass()
        self.remote_path = os.path.join(self.test_root_path, 'remote')
        self.new_remote_path = os.path.join(self.test_root_path, 'fooo')
        self.version = 'master'
        self.branch = 'test_branch'
        self.date = datetime.date.today().isoformat()
        os.makedirs(self.remote_path)

        create_git_repo(self.remote_path)

        # wstool the remote repo and fake ros
        entry = '''\
- other: {local-name: ../ros}
- git: {local-name: clone, uri: ../remote, version: %s}
''' % self.version
        _add_to_file(os.path.join(self.local_path, '.rosinstall'), entry)

        cmd = ['wstool', 'update', '-t', 'ws']
        os.chdir(self.test_root_path)
        wstool_main(cmd)

        self.clone_path = os.path.join(self.local_path, 'clone')

        modify_git_repo(self.clone_path)

        subprocess.check_call(['git', 'checkout', '-b', self.branch],
                              cwd=self.clone_path)
        subprocess.check_call(['git', 'remote', 'set-url', 'origin',
                               self.new_remote_path], cwd=self.clone_path)

    @staticmethod
    def exp(*args):
        return '''\
# THIS IS AN AUTOGENERATED FILE, LAST GENERATED USING wstool ON %s
- git:
    local-name: clone
    uri: %s
    version: %s

''' % args

    def helper(self, spec, exact, expected_output):
        cmd = ['wstool', 'export', '-t', 'ws']
        if spec:
            cmd += ['--spec']
        if exact:
            cmd += ['--exact']

        os.chdir(self.test_root_path)
        sys.stdout = output = StringIO()
        wstool_main(cmd)
        sys.stdout = sys.__stdout__
        output = output.getvalue().encode('utf-8')
        expected_output = expected_output.encode('utf-8')
        self.assertEqual(expected_output, output)

    def test_wstool_export(self):
        o = self.exp(self.date, self.new_remote_path, self.branch)
        self.helper(False, False, o)

    def test_wstool_export_spec(self):
        o = self.exp(self.date, self.remote_path, self.version)
        self.helper(True, False, o)

    def test_wstool_export_exact(self):
        uuid = get_git_hash(self.clone_path)
        o = self.exp(self.date, self.new_remote_path, uuid)
        self.helper(False, True, o)

    def test_wstool_export_spec_exact(self):
        uuid = get_git_hash(self.clone_path)
        o = self.exp(self.date, self.remote_path, uuid)
        self.helper(True, True, o)
