def test_case_clone(request, test_case_id):
    """ Clones an existing test case """

    testcase = TestCase.objects.get(id=test_case_id)
    author = request.user.username
    prior_id = None
    design_steps = None

    if request.method == 'POST':
        form = TestCaseForm(request.POST)
        if form.is_valid():
            tc = form.save()
            tc.save()
            steps = request.POST['designsteplist']
            if steps:
                steps_id = [int(item) for item in (steps.split(","))]
                design_steps = DesignStep.objects.filter(id__in=steps_id)
                for design_step in design_steps:
                    tc.design_steps.add(design_step)
                tc.save()
            return HttpResponseRedirect(reverse('case_view', args=(tc.id, )))

    else:
        design_steps = testcase.design_steps.all()
        design_steps_dict = list(design_steps.values(
        ))  # creating a dict since a queryset is immutable
        for index in range(0, len(design_steps)):
            clone_step = design_steps[index]
            clone_step.pk = None
            clone_step.save()
            design_steps_dict[index]["id"] = clone_step.pk
        design_steps = json.dumps(design_steps_dict)

        testcase.description = testcase.description + "\n\n\nCLONED FROM\n=============\ntestcase id: " + str(
            testcase.id) + "\ntestcase name: " + testcase.name
        folderid = testcase.folder_id
        folder_path = testcase.folder.folder_path()
        testcase.name = "CLONE OF " + testcase.name
        testcase.author = User.objects.get(username=author)
        prior_id = testcase.id
        testcase.id = None
        form = TestCaseForm(instance=testcase)

    return render_to_response('test_case_form.html', {
        'form': form,
        'type': 'View/Edit Test Case',
        'author': author,
        'gridData': design_steps,
        'test_case': testcase,
        'product_lookup': generate_product_lookup(),
        'id': None,
        'prior_id': prior_id,
        'folderid': folderid,
        'folder_path': folder_path,
        'clone': True,
    },
                              context_instance=RequestContext(request))
def test_case_edit(request, test_case_id=-1):
    updated_by = request.user.username
    if test_case_id == -1:
        testcase = None
        author = updated_by
    else:
        testcase = TestCase.objects.get(pk=test_case_id)
        author = testcase.author

    url_parameters = ""
    previous_testcase = None
    next_testcase = None

    if request.GET.get("navigate"):
        url_parameters += "?navigate=true"
        if request.GET.get("testplan"):
            url_parameters += "&testplan=" + request.GET.get("testplan")
            if request.GET.get("testplan_add"):
                url_parameters += "&testplan_add=true"
                previous_testcase = testcase.previous_testcase(
                    testplan_id=request.GET.get("testplan"), add_testplan=True
                )
                next_testcase = testcase.next_testcase(testplan_id=request.GET.get("testplan"), add_testplan=True)
            else:
                previous_testcase = testcase.previous_testcase(testplan_id=request.GET.get("testplan"))
                next_testcase = testcase.next_testcase(testplan_id=request.GET.get("testplan"))
        else:
            previous_testcase = testcase.previous_testcase()
            next_testcase = testcase.next_testcase()

    message = None

    if request.method == "POST":
        form = TestCaseForm(request.POST, instance=testcase)

        if form.is_valid():

            # prevent to create a duplicate testcase with same name in a folder.
            if (
                test_case_id == -1
                and TestCase.objects.filter(name=form.cleaned_data["name"], folder_id=request.POST["folder"]).exists()
            ):
                message = (
                    "The testcase name %s is already exsists. Please change it and try again."
                    % form.cleaned_data["name"]
                )
                messages.add_message(request, messages.ERROR, message)
                return render_to_response(
                    "test_case_form.html",
                    {
                        "form": form,
                        "type": "View/Edit Test Case",
                        "author": author,
                        "updated_by": updated_by,
                        "test_case": testcase,
                        "product_lookup": generate_product_lookup(),
                        "id": _set_tc_id(test_case_id),
                    },
                    context_instance=RequestContext(request),
                )
            else:
                tc = form.save()
                _add_steps(tc, request)
                _add_uploads(tc, request)
                testcase = tc
                testcase.updated_datetime = datetime.datetime.now(pytz.timezone("US/Pacific"))
                testcase.updated_by = User.objects.get(username=updated_by)
                testcase.save()

            if test_case_id == -1:
                message = "Created the testcase %s successfully" % tc.name
                author = updated_by
            else:
                message = "Edited the testcase %s successfully" % tc.name
                author = testcase.author
            messages.add_message(request, messages.SUCCESS, message)
            test_case_id = tc.id
            return HttpResponseRedirect(reverse("case_view", args=(tc.id,)))
        else:
            messages.add_message(
                request,
                messages.ERROR,
                "There was a problem submitting the form. Please check the values and try again.",
            )
            return render_to_response(
                "test_case_form.html",
                {
                    "form": form,
                    "type": "View/Edit Test Case",
                    "author": author,
                    "updated_by": updated_by,
                    "test_case": testcase,
                    "product_lookup": generate_product_lookup(),
                    "id": _set_tc_id(test_case_id),
                },
                context_instance=RequestContext(request),
            )
    else:
        if test_case_id == -1:
            folder_id = request.GET["folder_id"]
            author = request.user
        else:
            folder_id = testcase.folder_id

        if folder_id == "-100":
            folder = Folder.objects.get(name="root")
            folder_path = "/" + folder.name
        else:
            folder = Folder.objects.get(id=folder_id)
            folder_path = folder.folder_path()
        initial_value = {"author": author, "folder": folder, "folder_path": folder_path}
        form = TestCaseForm(instance=testcase, initial=initial_value)

    return render_to_response(
        "test_case_form.html",
        {
            "form": form,
            "type": "View/Edit Test Case",
            "author": author,
            "updated_by": updated_by,
            "test_case": testcase,
            "product_lookup": generate_product_lookup(),
            "foldername": folder,
            "folder_path": folder_path,
            "folderid": folder_id,
            "id": _set_tc_id(test_case_id),
            "previous_testcase": previous_testcase,
            "next_testcase": next_testcase,
            "url_parameters": url_parameters,
        },
        context_instance=RequestContext(request),
    )
def test_case_clone(request, test_case_id):
    """ Clones an existing test case """

    testcase = TestCase.objects.get(id=test_case_id)
    author = request.user.username
    prior_id = None
    design_steps = None

    if request.method == "POST":
        form = TestCaseForm(request.POST)
        if form.is_valid():
            tc = form.save()
            tc.save()
            steps = request.POST["designsteplist"]
            if steps:
                steps_id = [int(item) for item in (steps.split(","))]
                design_steps = DesignStep.objects.filter(id__in=steps_id)
                for design_step in design_steps:
                    tc.design_steps.add(design_step)
                tc.save()
            return HttpResponseRedirect(reverse("case_view", args=(tc.id,)))

    else:
        design_steps = testcase.design_steps.all()
        design_steps_dict = list(design_steps.values())  # creating a dict since a queryset is immutable
        for index in range(0, len(design_steps)):
            clone_step = design_steps[index]
            clone_step.pk = None
            clone_step.save()
            design_steps_dict[index]["id"] = clone_step.pk
        design_steps = json.dumps(design_steps_dict)

        testcase.description = (
            testcase.description
            + "\n\n\nCLONED FROM\n=============\ntestcase id: "
            + str(testcase.id)
            + "\ntestcase name: "
            + testcase.name
        )
        folderid = testcase.folder_id
        folder_path = testcase.folder.folder_path()
        testcase.name = "CLONE OF " + testcase.name
        testcase.author = User.objects.get(username=author)
        prior_id = testcase.id
        testcase.id = None
        form = TestCaseForm(instance=testcase)

    return render_to_response(
        "test_case_form.html",
        {
            "form": form,
            "type": "View/Edit Test Case",
            "author": author,
            "gridData": design_steps,
            "test_case": testcase,
            "product_lookup": generate_product_lookup(),
            "id": None,
            "prior_id": prior_id,
            "folderid": folderid,
            "folder_path": folder_path,
            "clone": True,
        },
        context_instance=RequestContext(request),
    )
def test_case_edit(request, test_case_id=-1):
    updated_by = request.user.username
    if test_case_id == -1:
        testcase = None
        author = updated_by
    else:
        testcase = TestCase.objects.get(pk=test_case_id)
        author = testcase.author

    message = None

    if request.method == 'POST':
        form = TestCaseForm(request.POST, instance=testcase)

        if form.is_valid():

            tc = form.save()
            _add_steps(tc, request)
            _add_uploads(tc, request)
            testcase = tc
            testcase.folder_path = generate_folder_path(request.POST['folder'])
            testcase.updated_datetime = datetime.datetime.now(pytz.timezone('US/Pacific'))
            testcase.updated_by = User.objects.get(username=updated_by)
            testcase.save()
            if test_case_id == -1:
                message = "Created the testcase %s successfully" % tc.name
                author = updated_by
            else:
                message = "Edited the testcase %s successfully" % tc.name
                author = testcase.author
            messages.add_message(request, messages.SUCCESS, message)
            test_case_id = tc.id
            return HttpResponseRedirect(reverse('case_view', args=(tc.id,)))
        else:
            messages.add_message(request, messages.ERROR, "There was a problem submitting the form. Please check the values and try again.")
            return render_to_response('test_case_form.html',
                                      {'form': form,
                                       'type': 'View/Edit Test Case',
                                       'author': author,
                                       'updated_by': updated_by,
                                       'test_case': testcase,
                                       'product_lookup': generate_product_lookup(),
                                       'id': _set_tc_id(test_case_id)
                                       },
                                      context_instance=RequestContext(request))
    else:
        if test_case_id == -1:
            folder_id = request.GET['folder_id']
            author = request.user
        else:
            folder_id = testcase.folder_id

        if folder_id == "-100":
            folder = Folder.objects.get(name="root")
            folder_path = "Subject/" + folder.name
        else:
            folder = Folder.objects.get(id=folder_id)
            folder_path = generate_folder_path(folder_id)
        initial_value = {'author': author, 'folder': folder, 'folder_path': folder_path}
        form = TestCaseForm(instance=testcase, initial=initial_value)

    return render_to_response('test_case_form.html',
                              {'form': form,
                               'type': 'View/Edit Test Case',
                               'author': author,
                               'updated_by': updated_by,
                               'test_case': testcase,
                               'product_lookup': generate_product_lookup(),
                               'foldername': folder,
                               'folder_path': folder_path,
                               'folderid': folder_id,
                               'id': _set_tc_id(test_case_id)
                               },
                              context_instance=RequestContext(request))
def test_case_edit(request, test_case_id=-1):
    updated_by = request.user.username
    if test_case_id == -1:
        testcase = None
        author = updated_by
    else:
        testcase = TestCase.objects.get(pk=test_case_id)
        author = testcase.author

    url_parameters = ""
    previous_testcase = None
    next_testcase = None

    if request.GET.get("navigate"):
        url_parameters += "?navigate=true"
        if request.GET.get("testplan"):
            url_parameters += "&testplan=" + request.GET.get("testplan")
            if request.GET.get("testplan_add"):
                url_parameters += "&testplan_add=true"
                previous_testcase = testcase.previous_testcase(
                    testplan_id=request.GET.get("testplan"), add_testplan=True)
                next_testcase = testcase.next_testcase(
                    testplan_id=request.GET.get("testplan"), add_testplan=True)
            else:
                previous_testcase = testcase.previous_testcase(
                    testplan_id=request.GET.get("testplan"))
                next_testcase = testcase.next_testcase(
                    testplan_id=request.GET.get("testplan"))
        else:
            previous_testcase = testcase.previous_testcase()
            next_testcase = testcase.next_testcase()

    message = None

    if request.method == 'POST':
        form = TestCaseForm(request.POST, instance=testcase)

        if form.is_valid():

            # prevent to create a duplicate testcase with same name in a folder.
            if test_case_id == -1 and TestCase.objects.filter(
                    name=form.cleaned_data['name'],
                    folder_id=request.POST['folder']).exists():
                message = "The testcase name %s is already exsists. Please change it and try again." % \
                          form.cleaned_data['name']
                messages.add_message(request, messages.ERROR, message)
                return render_to_response(
                    'test_case_form.html', {
                        'form': form,
                        'type': 'View/Edit Test Case',
                        'author': author,
                        'updated_by': updated_by,
                        'test_case': testcase,
                        'product_lookup': generate_product_lookup(),
                        'id': _set_tc_id(test_case_id)
                    },
                    context_instance=RequestContext(request))
            else:
                tc = form.save()
                _add_steps(tc, request)
                _add_uploads(tc, request)
                testcase = tc
                testcase.updated_datetime = datetime.datetime.now(
                    pytz.timezone('US/Pacific'))
                testcase.updated_by = User.objects.get(username=updated_by)
                testcase.save()

            if test_case_id == -1:
                message = "Created the testcase %s successfully" % tc.name
                author = updated_by
            else:
                message = "Edited the testcase %s successfully" % tc.name
                author = testcase.author
            messages.add_message(request, messages.SUCCESS, message)
            test_case_id = tc.id
            return HttpResponseRedirect(reverse('case_view', args=(tc.id, )))
        else:
            messages.add_message(
                request, messages.ERROR,
                "There was a problem submitting the form. Please check the values and try again."
            )
            return render_to_response(
                'test_case_form.html', {
                    'form': form,
                    'type': 'View/Edit Test Case',
                    'author': author,
                    'updated_by': updated_by,
                    'test_case': testcase,
                    'product_lookup': generate_product_lookup(),
                    'id': _set_tc_id(test_case_id)
                },
                context_instance=RequestContext(request))
    else:
        if test_case_id == -1:
            folder_id = request.GET['folder_id']
            author = request.user
        else:
            folder_id = testcase.folder_id

        if folder_id == "-100":
            folder = Folder.objects.get(name="root")
            folder_path = "/" + folder.name
        else:
            folder = Folder.objects.get(id=folder_id)
            folder_path = folder.folder_path()
        initial_value = {
            'author': author,
            'folder': folder,
            'folder_path': folder_path
        }
        form = TestCaseForm(instance=testcase, initial=initial_value)

    return render_to_response('test_case_form.html', {
        'form': form,
        'type': 'View/Edit Test Case',
        'author': author,
        'updated_by': updated_by,
        'test_case': testcase,
        'product_lookup': generate_product_lookup(),
        'foldername': folder,
        'folder_path': folder_path,
        'folderid': folder_id,
        'id': _set_tc_id(test_case_id),
        'previous_testcase': previous_testcase,
        'next_testcase': next_testcase,
        'url_parameters': url_parameters
    },
                              context_instance=RequestContext(request))