#!/usr/bin/env python
import sys, os, time
import difflib
import unittest

import sublime


"""
Detect SublimeText version to deal w/ v2 vs v3 deltas
"""
version = sublime.version()
print("Testing with SublimeText version: %s" % version)


"""
For plugin helper functions, load them so we can hit functionality
within the plugin
"""
if version < "3000":
    clipboard_diff = sys.modules["clipboard_diff"]
else:
    clipboard_diff = sys.modules["sublime-clipboard-diff.clipboard_diff"]


"""
Python 2 vs Python 3 - Compatibility:
  * reduce() is functools.reduce
"""
try:
    # Python 2
    _reduce = reduce
except NameError:
    # Python 3
    import functools
    _reduce = functools.reduce


class TestSelectionDiffPlugin(unittest.TestCase):
    """
    Unit tests to validate sublime-selection-diff plugin methods
    """

    test_lines_0 = "line 0\nline 1\nline 2"
    test_lines_1 = "line A\nline 1"


    """
    Helper functions
    """
    def getDiffExpectedResult(self, diff_fn, str_a, str_b, file_a, file_b):
        result = diff_fn(
                    clipboard_diff.getLinesHelper(str_a),
                    clipboard_diff.getLinesHelper(str_b),
                    file_a, file_b)
        return _reduce(lambda acc, x: acc + x, result, "")

    def runSimpleViewCommand(self, cmd):
        if self.test_view:
            self.test_view.run_command(cmd)

    def insertTextToTestView(self, text):
        self.test_view.run_command("insert", {"characters": text})


    """
    Setup / Teardown
    """
    def setUp(self):
        """
        Common setUp() for TestSelectionDiffPlugin
        """
        self.test_view = sublime.active_window().new_file()
        self.test_view.set_name("Test View")
        self.test_view.set_scratch(True)

        self.settings = sublime.load_settings("clipboard_diff.sublime-settings")


    def tearDown(self):
        """
        Common tearDown() for TestSelectionDiffPlugin
        """
        test_window = self.test_view.window()
        test_window.focus_view(self.test_view)
        test_window.run_command("close_file")


    """
    Helper Function Tests:
    """
    def test_get_selection_str(self):
        """
        Validate the selectionToString helper
        """
        self.insertTextToTestView(self.test_lines_0)
        self.runSimpleViewCommand("select_all")

        selection_txt = clipboard_diff.selectionToString(self.test_view)

        self.assertEqual(self.test_lines_0, selection_txt)

    def test_line_helper(self):
        """
        Validates the line helper
        """
        lines = clipboard_diff.getLinesHelper(self.test_lines_0)

        self.assertEqual(len(lines), 3)
        self.assertEqual(lines[0], "line 0\n")
        self.assertEqual(lines[1], "line 1\n")
        self.assertEqual(lines[2], "line 2\n")

    if version < "3000":
        """
        Tests ST2 only stuff
        """