//
//  EMFileViewController.m
//  FileExample
//
//  Created by Dexter Weiss on 10/11/13.
//  Copyright (c) 2013 Emmoco. All rights reserved.
//

#import "EMFileViewController.h"
#import "EMFramework.h"

@interface EMFileViewController () <UITextViewDelegate> {
    IBOutlet UITextView *_readTextFile;
    IBOutlet UITextField *_numberOfBytesField;
}

@end

@implementation EMFileViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [_readTextFile setText:nil];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Interface Actions

-(IBAction)readButtonPressed:(id)sender {
    [[EMConnectionManager sharedManager] readResource:@"fileData" onSuccess:^(id readValue) {
        NSLog(@"%@", readValue);
        [_readTextFile setText:[readValue description]];
        NSString *bytesString = [readValue length] == 1 ? @"byte" : @"bytes";
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Success" message:[NSString stringWithFormat:@"Successfully read %d %@", [readValue length], bytesString] delegate:nil cancelButtonTitle:@"Sweet!" otherButtonTitles:nil];
        [alert show];
    } onFail:^(NSError *error) {
        
    }];
}

-(IBAction)sliderValueChanged:(UISlider *)sender {
    [_numberOfBytesField setText:[NSString stringWithFormat:@"%0.0f", [sender value]]];
}

-(IBAction)writeButtonPressed:(id)sender {
    NSInteger numberOfBytes = [[_numberOfBytesField text] integerValue];
    
    [[EMConnectionManager sharedManager] writeValue:[NSNumber numberWithInt:numberOfBytes] toResource:@"fileSize" onSuccess:^{
        
        UInt8 *integerArray = malloc(numberOfBytes);
        for (NSInteger i = 0; i < numberOfBytes; ++i) {
            integerArray[i] = i;
        }
        
        NSData *data = [NSData dataWithBytes:integerArray length:numberOfBytes];
        NSString *bytesString = numberOfBytes == 1 ? @"byte" : @"bytes";
        
        [[EMConnectionManager sharedManager] writeValue:data toResource:@"fileData" onSuccess:^{
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Success" message:[NSString stringWithFormat:@"Successfully wrote %d %@", numberOfBytes, bytesString] delegate:nil cancelButtonTitle:@"Sweet!" otherButtonTitles:nil];
            [alert show];
        } onFail:^(NSError *error) {
            
        }];
        
    } onFail:^(NSError *error) {
        
    }];
}

#pragma mark - Text View Delegate

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    if ([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
        return NO;
    }
    return YES;
}

@end
