#include <stdio.h>
#include <string.h>
#include <pslib.h>

#include "tap.h"
#include "pstap.h"

#define ORIGINAL "This is, a, test case, to check."
#define CORRECTED "This is a test case to check."

int main (void)
{
    plan_tests(16);

    diag("psStringSubstitute() tests");

    // Return input for NULL key
    {
        psString input = psStringCopy(ORIGINAL);
        input = psStringSubstitute(input, ",", NULL);
        ok(input && strcmp(input, ORIGINAL) == 0, "output = %s", input);
        psFree(input);
        //        ok(psMemCheckLeaks(0, NULL, stdout, false) == 0, "Memory Leaks");
        mem();
    }

    // Return input for empty key
    {
        psString input = psStringCopy(ORIGINAL);
        input = psStringSubstitute(input, "XXX", "");
        ok(input && strcmp(input, ORIGINAL) == 0, "output = %s", input);
        psFree(input);
        //        ok(psMemCheckLeaks(0, NULL, stdout, false) == 0, "Memory Leaks");
        mem();
    }

    // Return corrected version for NULL replace
    {
        psString input = psStringCopy(ORIGINAL);
        psString output = psStringSubstitute(input, NULL, ",");
        ok(output && strcmp(output, CORRECTED) == 0, "output = %s", output);
        psFree(output);
        mem();
    }

    // Return corrected version for empty replace
    {
        psString input = psStringCopy(ORIGINAL);
        psString output = psStringSubstitute(input, "", ",");
        ok(output && strcmp(output, CORRECTED) == 0, "output = %s", output);
        psFree(output);
        mem();
    }

    // Return NULL for NULL input
    {
        psString output = psStringSubstitute(NULL, "XXX", ",");
        ok(!output, "output = %s", output);
        mem();
    }

    // Return emptry string for empty input
    {
        psString input = psStringCopy("");
        psString output = psStringSubstitute(input, "XXX", ",");
        ok(output && strcmp(output, input) == 0, "output = %s", output);
        psFree(output);
        mem();
    }

    // Change commas to bangs
    {
        psString input = psStringCopy(ORIGINAL);
        psString output = psStringSubstitute(input, "!", ",");
        ok(output && strcmp(output, "This is! a! test case! to check.") == 0, "output = %s", output);
        psFree(output);
        mem();
    }

    // Long replacement text --- should allocate new space
    {
        psString input = psStringCopy(ORIGINAL);
        psString output = psStringSubstitute(input, "; This string is too long to fit in input(35 chars)", ".");
        ok(output && strcmp(output, "This is, a, test case, to check; "
                            "This string is too long to fit in input(35 chars)") == 0,
           "output = %s", output);
        psFree(output);
        mem();
    }


    return exit_status();
}
