//
//  PBAdvertiseBeaconViewController.m
//  PolytechBeacon
//
//  Created by Kinan on 15/11/14.
//  Copyright (c) 2014 Kinan Arnaout. All rights reserved.
//

#import "PBAdvertiseBeaconViewController.h"
@import CoreLocation;
@import CoreBluetooth;

@interface PBAdvertiseBeaconViewController () <CBPeripheralManagerDelegate>
@property (weak, nonatomic) IBOutlet UITextField *uuidTextField;
@property (weak, nonatomic) IBOutlet UITextField *majorTextField;
@property (weak, nonatomic) IBOutlet UITextField *minorTextField;
@property (weak, nonatomic) IBOutlet UISwitch *advertiseSwitch;

@property (strong, nonatomic) CBPeripheralManager *peripheralManager;
@property (strong, nonatomic) CLBeaconRegion *region;

@end

@implementation PBAdvertiseBeaconViewController

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

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
}

- (void)viewWillAppear:(BOOL)animated
{
    self.peripheralManager = [[CBPeripheralManager alloc] initWithDelegate:self queue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) options:nil];
    self.peripheralManager.delegate = self;

}


- (void)viewWillDisappear:(BOOL)animated
{
    self.peripheralManager.delegate = nil;
}


- (IBAction)enableSwitchUpdateState:(UISwitch *)sender {
    
    if (sender.on) {
        if(self.peripheralManager.state == CBPeripheralManagerStatePoweredOn)
        {
            
            //NSUUID *beaconUUID = [[NSUUID alloc] initWithUUIDString:@"B9407F30-F5F8-466E-AFF9-25556B57FE6D"];
            NSUUID *beaconUUID = [[NSUUID alloc] initWithUUIDString:self.uuidTextField.text];
            
            self.region = [[CLBeaconRegion alloc] initWithProximityUUID:beaconUUID major:[self.majorTextField.text intValue] minor:[self.minorTextField.text intValue] identifier:beaconUUID.UUIDString];
            
            NSDictionary *beaconPeripheral = [self.region peripheralDataWithMeasuredPower:@(-50)];
            [self.peripheralManager startAdvertising:beaconPeripheral];
            
        } else {
            NSString *title = @"Bluetooth must be enabled";
            NSString *message = @"To configure your device as a beacon";
            NSString *cancelButtonTitle = @"OK";
            UIAlertView *errorAlert = [[UIAlertView alloc] initWithTitle:title message:message delegate:self cancelButtonTitle:cancelButtonTitle otherButtonTitles:nil];
            [errorAlert show];
            
        }
    } else {
        [self.peripheralManager stopAdvertising];
    }
}


- (void)peripheralManagerDidUpdateState:(CBPeripheralManager *)peripheral
{
    
}

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



@end
