#import <UIKit/UIKit.h>
#import <WebKit/WKNavigationDelegate.h>
#import <WebKit/WKUIDelegate.h>
#import <WebKit/WKWebView.h>
#import <WebKit/WKWebViewConfiguration.h>

#include "log.h"

#include <libgen.h>
#include <string.h>

void tf_run_thread_start(const char* zip_path);

@interface ViewController : UINavigationController <WKUIDelegate, WKNavigationDelegate>
@property (strong, nonatomic) WKWebView* web_view;
@property bool initial_load_complete;
@end

static void _start_initial_load(WKWebView* web_view)
{
	[web_view loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://localhost:12345/login/auto"]]];
}

@implementation ViewController : UINavigationController
- (void)viewDidLoad
{
	[super viewDidLoad];

	[self setToolbarHidden:false animated:false];
	self.toolbar.items = @[
		[[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonItemStylePlain target:self action:@selector(goBack)],
		[[UIBarButtonItem alloc] initWithTitle:@"Forward" style:UIBarButtonItemStylePlain target:self action:@selector(goForward)],
		[[UIBarButtonItem alloc] initWithTitle:@"Refresh" style:UIBarButtonItemStylePlain target:self action:@selector(reload)]
	];

	WKWebViewConfiguration* configuration = [[WKWebViewConfiguration alloc] init];
	self.web_view = [[WKWebView alloc] initWithFrame:self.view.frame configuration:configuration];
	self.web_view.UIDelegate = self;
	self.web_view.navigationDelegate = self;
	self.web_view.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
	self.web_view.translatesAutoresizingMaskIntoConstraints = false;
	[self.view addSubview:self.web_view];

	[self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.web_view attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.view
														  attribute:NSLayoutAttributeTop
														 multiplier:1.0
														   constant:0]];
	[self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.web_view attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.view
														  attribute:NSLayoutAttributeBottom
														 multiplier:1.0
														   constant:-75]];
	[self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.web_view attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.view
														  attribute:NSLayoutAttributeLeft
														 multiplier:1.0
														   constant:0]];
	[self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.web_view attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:self.view
														  attribute:NSLayoutAttributeRight
														 multiplier:1.0
														   constant:0]];

	_start_initial_load(self.web_view);
}

- (void)goBack
{
	if (self.web_view.canGoBack)
	{
		[self.web_view goBack];
	}
}

- (void)goForward
{
	if (self.web_view.canGoForward)
	{
		[self.web_view goForward];
	}
}

- (void)reload
{
	[self.web_view reload];
}

- (void)webView:(WKWebView*)webView didFinishNavigation:(WKNavigation*)navigation
{
	self.initial_load_complete = true;
}

- (void)webView:(WKWebView*)webView didFailProvisionalNavigation:(WKNavigation*)navigation withError:(NSError*)error
{
	if (!self.initial_load_complete)
	{
		_start_initial_load(self.web_view);
	}
}

- (void)webView:(WKWebView*)webView
	runJavaScriptConfirmPanelWithMessage:(NSString*)message
						initiatedByFrame:(WKFrameInfo*)frame
					   completionHandler:(void (^)(BOOL result))completionHandler
{
	UIAlertController* alertController = [UIAlertController alertControllerWithTitle:message message:nil preferredStyle:UIAlertControllerStyleAlert];
	[alertController addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction* action) { completionHandler(true); }]];
	[alertController addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction* action) { completionHandler(false); }]];
	[self presentViewController:alertController animated:YES completion:^ {}];
}

- (void)webView:(WKWebView*)webView runJavaScriptAlertPanelWithMessage:(NSString*)message initiatedByFrame:(WKFrameInfo*)frame completionHandler:(void (^)(void))completionHandler
{
	UIAlertController* alertController = [UIAlertController alertControllerWithTitle:message message:nil preferredStyle:UIAlertControllerStyleAlert];
	[alertController addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction* action) { completionHandler(); }]];
	[self presentViewController:alertController animated:YES completion:^ {}];
}

- (void)webView:(WKWebView*)webView
	runJavaScriptTextInputPanelWithPrompt:(NSString*)prompt
							  defaultText:(NSString*)defaultText
						 initiatedByFrame:(WKFrameInfo*)frame
						completionHandler:(void (^)(NSString*))completionHandler
{
	NSString* sender = [NSString stringWithFormat:@"%@", self.web_view.URL.host];

	UIAlertController* alertController = [UIAlertController alertControllerWithTitle:prompt message:sender preferredStyle:UIAlertControllerStyleAlert];
	[alertController addTextFieldWithConfigurationHandler:^(UITextField* textField) {
		textField.placeholder = defaultText;
		textField.text = defaultText;
	}];
	[alertController addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction* action) {
		NSString* input = ((UITextField*)alertController.textFields.firstObject).text;
		completionHandler(input);
	}]];
	[alertController addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction* action) { completionHandler(nil); }]];
	[self presentViewController:alertController animated:YES completion:^ {}];
}
@end

@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow* window;
@end

@implementation AppDelegate
- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions
{
	self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
	ViewController* view_controller = [[ViewController alloc] init];
	self.window.rootViewController = view_controller;
	[self.window makeKeyAndVisible];
	return YES;
}
@end

int main(int argc, char* argv[])
{
	NSFileManager* file_manager = [NSFileManager defaultManager];
	NSString* library_directory = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0];
	[file_manager changeCurrentDirectoryPath:library_directory];
	size_t path_length = strlen(argv[0]) - strlen(basename(argv[0]));
	size_t length = path_length + strlen("data.zip");
	char* zip_path = alloca(length + 1);
	snprintf(zip_path, length + 1, "%.*sdata.zip", (int)path_length, argv[0]);
	tf_run_thread_start(zip_path);
	return UIApplicationMain(argc, argv, nil, @"AppDelegate");
}
