//
//  NAAppDelegate.m
//  NativeAutomationRunner
//
//  Created by Stanislaw Pankevich on 31/10/13.
//  Copyright (c) 2013 Stanislaw Pankevich. All rights reserved.
//

#import "NAAppDelegate.h"

static NSString * const AppName = @"NativeAutomationApp";
static NSString * const NativeAutomationAppPath = @"/Users/Stanislaw/Work/Pods/NativeAutomation/NativeAutomationApp";

static inline NSString * buildPath() {
    return [@[ NSTemporaryDirectory(), AppName ] componentsJoinedByString:@""];
}

NSTask *pwd(void) {
    NSTask *task = [[NSTask alloc] init];

    task.launchPath = @"/bin/pwd";
    task.arguments = @[];

    [task launch];

    return task;
}

NSTask *xcodebuildNativeAutomationApp(void) {
    NSString *pathToWorkspace = [@[NativeAutomationAppPath, @"NativeAutomationApp.xcworkspace"] componentsJoinedByString:@"/"];

    NSString *configurationBuildDirArgument = [NSString stringWithFormat:@"CONFIGURATION_BUILD_DIR=%@", buildPath()];

    NSTask *task = [[NSTask alloc] init];

    task.launchPath = @"/usr/bin/xcodebuild";

    task.arguments = @[
        @"-workspace", pathToWorkspace,
        @"-scheme", AppName,
        @"-sdk", @"iphonesimulator7.0",
        @"-configuration", @"'Release'",
        configurationBuildDirArgument
    ];

    NSLog(@"Resulting arguments: %@", [task.arguments componentsJoinedByString:@" "]);

    return task;
}

NSTask *launchSimulator(void) {
    NSString *pathToAppBundle = [[@[buildPath(), AppName] componentsJoinedByString:@"/"] stringByAppendingPathExtension:@"app"];

    NSTask *task = [[NSTask alloc] init];

    task.launchPath = @"/usr/local/bin//ios-sim";

    task.arguments = @[ @"launch", pathToAppBundle, @"--sdk", @"7.0" ];

    NSLog(@"Resulting arguments: %@", [task.arguments componentsJoinedByString:@" "]);
    
    return task;
}

@implementation NAAppDelegate

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    /*
    NSString *myPath = [[NSBundle mainBundle] bundlePath];
    NSString *curDir = [[NSFileManager defaultManager] currentDirectoryPath];

    NSLog(@"[[NSBundle mainBundle] bundlePath] %@", myPath);
    NSLog(@"[[NSFileManager defaultManager] currentDirectoryPath] %@", curDir);

     */

    //NSURL *appURL = [NSURL URLWithString:@"$(BUILT_PRODUCTS_DIR)/NativeAutomationApp.app/NativeAutomationApp"];

    [pwd() waitUntilExit];

    NSTask *xcodebuildTask = xcodebuildNativeAutomationApp();
    [xcodebuildTask launch];
    [xcodebuildTask waitUntilExit];

    int status = [xcodebuildTask terminationStatus];

    if (status == 0)
        NSLog(@"xcodebuildTask succeeded.");
    else
        NSLog(@"xcodebuildTask failed.");

    NSTask *simulatorTask = launchSimulator();
    [simulatorTask launch];
    [simulatorTask waitUntilExit];

    status = [simulatorTask terminationStatus];

    if (status == 0)
        NSLog(@"simulatorTask succeeded.");
    else
        NSLog(@"simulatorTask failed.");

//    NSLog(@"Lala %@", [task standardOutput]);
}

@end
