/*---------------------------------------------------------------------------*/
/* iphoneTests.m                                                             */
/* copyright (c) innovaphone 2015                                            */
/*                                                                           */
/*---------------------------------------------------------------------------*/

#import <XCTest/XCTest.h>
#import <UIKit/UIKit.h>
#import <stdio.h>

#define DO_QUOTE(X)     #X
#define QUOTE(X)        DO_QUOTE(X)
#define BUILD_STRING    QUOTE(BUILD)

@interface iphoneTests : XCTestCase

@end

@implementation iphoneTests

- (void)setUp
{
    [super setUp];
    // Put setup code here. This method is called before the invocation of each test method in the class.
}

- (void)tearDown
{
    // Put teardown code here. This method is called after the invocation of each test method in the class.
    [super tearDown];
}

- (void)testExample
{
    NSArray *dirPaths;
    NSString *libDir, *TestBuildPath;
	BOOL isDir;
    int test_build_fd, i;
    char test_build_string[32];

    dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    libDir = [dirPaths firstObject];
 
	NSFileManager *fileManager = [NSFileManager defaultManager];

	if (![fileManager fileExistsAtPath:libDir isDirectory:&isDir]){ 
		if(![fileManager createDirectoryAtPath:libDir withIntermediateDirectories:YES attributes:nil error:NULL]){
		}
	}

    TestBuildPath = [libDir stringByAppendingString:@"TestBuild"];
    test_build_fd = open(TestBuildPath.UTF8String, O_RDONLY);
    i = 0;
    if (test_build_fd != -1) {
        i = (int)(read(test_build_fd, test_build_string, sizeof(test_build_string) - 1));
        close(test_build_fd);
    }
    test_build_string[i] = '\0';
    test_build_fd = open(TestBuildPath.UTF8String, O_WRONLY | O_CREAT | O_TRUNC, S_IREAD | S_IWRITE);;
    if (test_build_fd != -1) {
        write(test_build_fd, BUILD_STRING, strlen(BUILD_STRING));
        close(test_build_fd);
    }

    if (strcmp(test_build_string, BUILD_STRING) != 0) {
        if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"phoneiosrestart:"]]) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"phoneiosrestart:"]];
        }
    }
    else {
        XCTestExpectation *neverOccuringExpectation = [self expectationWithDescription:@"neverOccuringExpectation"];

        // The test will pause here, running the run loop, until the timeout is hit
        // or all expectations are fulfilled.
        [self waitForExpectationsWithTimeout:0 handler:^(NSError *error) {
        }];

        [neverOccuringExpectation fulfill];
    }
}

@end
