//
//  ViewController.m
//  JoywayBeacon
//
//  Created by Bob Xia on 2018/7/3.
//  Copyright © 2018年 Bob Xia. All rights reserved.
//

#import "ViewController.h"
#import "BT.h"
#import "BTEvtDelegate.h"
#import "UserlDefind.h"
#import "Function_define.h"
#import <UIKit/UIColor.h>
#import "EddystoneConfigParam.h"
#import "iBeaconConfigViewController.h"

@interface ViewController () <BTEvtDelegate >
{
    UIButton * m_bnStart;
    UIButton * m_bnStop;
    UIButton * m_bnConfigIBeacon;
    UISegmentedControl * m_scMode;

    UITextField * m_tfUID_namespace;
    UITextField * m_tfUID_instance;
    UITextField * m_tfURL;
    UITextField * m_tfTX_interval_ms;
    UITextField * m_tfTX_power_db;
    
    UILabel * m_lblMac;
    UITextView * m_tvStatus;
    UIView * m_vEddystoneParams;    

}


@end


@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    [self.view setBackgroundColor:([UIColor colorWithRed:0.9 green:0.9 blue:1.0 alpha:1])];
    
    if (m_tfUID_namespace == nil)
    {
        int left = 5;
        int top = 60;
        int sizeX = SCREEN_WIDTH - left * 2;
        int sizeY = 30;
        int offsetY = 60;
        
        UILabel * lblTitle = [[UILabel alloc] initWithFrame:(CGRectMake(0, 28, SCREEN_WIDTH, 40))];
        [lblTitle setText:@"JOYWAY BEACON"];
        [lblTitle setFont:[UIFont fontWithName:@"Arial" size:24.0f ]];
        [lblTitle setTextAlignment:NSTextAlignmentCenter];
        [self.view addSubview:lblTitle];
        
        m_scMode = [[UISegmentedControl alloc] initWithItems:@[@"Eddystone", @"iBeacon"]];
        m_scMode.frame = CGRectMake(left, top, sizeX, 40);
        [m_scMode addTarget:self action:@selector(onScModeChanged:) forControlEvents:UIControlEventValueChanged];
        [self.view addSubview:m_scMode];
        
        m_vEddystoneParams = [[UIView alloc] initWithFrame:CGRectMake(0, top + 50, SCREEN_WIDTH, offsetY * 4)];
        m_vEddystoneParams.backgroundColor = [UIColor clearColor];
        
        UILabel * lblUID_namespace = [[UILabel alloc] initWithFrame:CGRectMake(left, 0, sizeX, sizeY)];
        UILabel * lblUID_instance = [[UILabel alloc] initWithFrame:CGRectMake(left, offsetY * 1, sizeX, sizeY)];
        UILabel * lblURL = [[UILabel alloc] initWithFrame:CGRectMake(left + sizeX / 2 + 10, offsetY * 1, sizeX, sizeY)];
        UILabel * lblTX_interval_ms = [[UILabel alloc] initWithFrame:CGRectMake(left, offsetY * 2, sizeX, sizeY)];
        UILabel * lblTX_Power_db = [[UILabel alloc] initWithFrame:CGRectMake(left + sizeX / 2 + 10, offsetY * 2, sizeX, sizeY)];
        UILabel * lblMac = [[UILabel alloc] initWithFrame:CGRectMake(left, offsetY * 3, sizeX, sizeY)];
        
        [lblUID_namespace setText:@"UID Namespace"];
        [lblUID_instance setText:@"UID Instance"];
        [lblURL setText:@"URL"];
        [lblTX_interval_ms setText:@"TX Interval (ms)"];
        [lblTX_Power_db setText:@"TX Power (db)"];
        [lblMac setText:@"Mac"];
        [m_vEddystoneParams addSubview:lblUID_namespace];
        [m_vEddystoneParams addSubview:lblUID_instance];
        [m_vEddystoneParams addSubview:lblURL];
        [m_vEddystoneParams addSubview:lblTX_interval_ms];
        [m_vEddystoneParams addSubview:lblTX_Power_db];
        [m_vEddystoneParams addSubview:lblMac];
        
        m_tfUID_namespace = [[UITextField alloc] initWithFrame:CGRectMake(left, sizeY, sizeX, sizeY)];
        m_tfUID_instance = [[UITextField alloc] initWithFrame:CGRectMake(left, sizeY + offsetY * 1, sizeX / 2 - 10, sizeY)];
        m_tfURL = [[UITextField alloc] initWithFrame:CGRectMake(left + sizeX / 2 + 10, sizeY + offsetY * 1, sizeX / 2 - 10, sizeY)];
        m_tfTX_interval_ms = [[UITextField alloc] initWithFrame:CGRectMake(left, sizeY + offsetY * 2, sizeX / 2 - 10, sizeY)];
        m_tfTX_power_db = [[UITextField alloc] initWithFrame:CGRectMake(left + sizeX / 2 + 10, sizeY + offsetY * 2, sizeX / 2 - 10, sizeY)];
        m_lblMac = [[UILabel alloc] initWithFrame:CGRectMake(left, sizeY + offsetY * 3, sizeX, sizeY)];
        
        [m_tfUID_namespace setBorderStyle:UITextBorderStyleRoundedRect];
        [m_tfUID_namespace setBackgroundColor:[UIColor whiteColor]];
        [m_tfUID_instance setBorderStyle:UITextBorderStyleRoundedRect];
        [m_tfUID_instance setBackgroundColor:[UIColor whiteColor]];
        [m_tfURL setBorderStyle:UITextBorderStyleRoundedRect];
        [m_tfURL setBackgroundColor:[UIColor whiteColor]];
        [m_tfTX_interval_ms setBorderStyle:UITextBorderStyleRoundedRect];
        [m_tfTX_interval_ms setBackgroundColor:[UIColor whiteColor]];
        [m_tfTX_power_db setBorderStyle:UITextBorderStyleRoundedRect];
        [m_tfTX_power_db setBackgroundColor:[UIColor whiteColor]];
        [m_lblMac setBackgroundColor:[UIColor whiteColor]];
        [m_lblMac setAdjustsFontSizeToFitWidth:TRUE];
        
        [m_vEddystoneParams addSubview:m_tfUID_namespace];
        [m_vEddystoneParams addSubview:m_tfUID_instance];
        [m_vEddystoneParams addSubview:m_tfURL];
        [m_vEddystoneParams addSubview:m_tfTX_interval_ms];
        [m_vEddystoneParams addSubview:m_tfTX_power_db];
        [m_vEddystoneParams addSubview:m_lblMac];
        
        [self.view addSubview:m_vEddystoneParams];
        
        m_tvStatus = [[UITextView alloc] initWithFrame:CGRectMake(left, top + offsetY * 5 + 60, sizeX, sizeY*2)];
        [m_tvStatus setText:@"Tips: 1, Reinstall the battery of the beacon device, this will make the device going to config mode. 2, Change above parameters, then press Start button to search and config beacon."];
        [m_tvStatus setBackgroundColor: [UIColor clearColor]];
        [m_tvStatus setEditable:FALSE];
        [self.view addSubview:m_tvStatus];
        
        m_bnStart = [[UIButton alloc] initWithFrame:CGRectMake(left, top + sizeY*2 + offsetY * 5 + 100, 120, 45)];
        [m_bnStart setTitle:@"Start" forState:UIControlStateNormal];
        [m_bnStart setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [m_bnStart.titleLabel setFont:[UIFont systemFontOfSize:16]];
        [m_bnStart setBackgroundColor:[[UIColor greenColor] colorWithAlphaComponent:0.1]];
        m_bnStart.layer.cornerRadius = 8;
        m_bnStart.layer.borderWidth = 0.5;
        m_bnStart.layer.borderColor = [[UIColor lightGrayColor] CGColor];
        [m_bnStart addTarget:self action:@selector(onBnStartClicked) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:m_bnStart];
    
        m_bnStop = [[UIButton alloc] initWithFrame:CGRectMake(left + 130, top + sizeY*2 + offsetY * 5 + 100, 120, 45)];
        [m_bnStop setTitle:@"Stop" forState:UIControlStateNormal];
        [m_bnStop setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [m_bnStop.titleLabel setFont:[UIFont systemFontOfSize:16]];
        [m_bnStop setBackgroundColor:[[UIColor redColor] colorWithAlphaComponent:0.1]];
        m_bnStop.layer.cornerRadius = 8;
        m_bnStop.layer.borderWidth = 0.5;
        m_bnStop.layer.borderColor = [[UIColor lightGrayColor] CGColor];
        [m_bnStop addTarget:self action:@selector(onBnStopClicked) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:m_bnStop];

        m_bnConfigIBeacon = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - left - 120, top + sizeY*2 + offsetY * 5 + 100, 120, 45)];
        [m_bnConfigIBeacon setTitle:@"Config iBeacon" forState:UIControlStateNormal];
        [m_bnConfigIBeacon setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [m_bnConfigIBeacon.titleLabel setFont:[UIFont systemFontOfSize:16]];
        [m_bnConfigIBeacon setBackgroundColor:[[UIColor grayColor] colorWithAlphaComponent:0.1]];
        m_bnConfigIBeacon.layer.cornerRadius = 8;
        m_bnConfigIBeacon.layer.borderWidth = 0.5;
        m_bnConfigIBeacon.layer.borderColor = [[UIColor lightGrayColor] CGColor];
        [m_bnConfigIBeacon addTarget:self action:@selector(onBnConfigIBeaconClicked) forControlEvents:UIControlEventTouchUpInside];
        [m_bnConfigIBeacon setHidden:YES];
        [self.view addSubview:m_bnConfigIBeacon];
        
        [m_tfUID_namespace setText:@"00010203040506070809"];
        [m_tfUID_instance setText:@"000102030405"];
        [m_tfURL setText:@"adv7.cn"];
        [m_tfTX_interval_ms setText:@"500"];
        [m_tfTX_power_db setText:@"0"];
        
    
        [BT initModuleWithReadingRssiTimeInterval:1.0];
        [BT listenBTEvent:self listen:TRUE];
        [BT startScanAllowDuplicatesKey:NO serviceUUIDs:nil];
        
        // only for testing
        /*EddystoneConfigParam* param = [EddystoneConfigParam alloc];
        param._uidNamespace = tfUID_namespace.text;
        param._uidInstance = tfUID_instance.text;
        param._url = tfURL.text;
        param._txPower = [tfTX_power_db.text intValue];
        param._txInterval = [tfTX_interval_ms.text intValue];
        param._https_or_http = TRUE;
        NSMutableArray<NSData*>* datas = [param getBytesDataListToSend];
        for (NSData* data in datas)
        {
            //[BT sendDataToTag:tagMac dataToSend:data];
            NSMutableData * data2 = [NSMutableData alloc];
            const char* pBytes = [data bytes];
            for (int i = 0 ; i < [data length]; i++)
            {
                [data2 appendBytes:(unsigned char*) &pBytes[i] length:1];
            }
            
            
        }*/
        //--------------------
        
    }
}


 -(void) onBnStartClicked
{
    [BT startScanAllowDuplicatesKey:NO serviceUUIDs:nil];
    
    [m_tvStatus setText:@"Status: Searching a nearby configurable device ... "];
    
}

-(void) onBnStopClicked
{
    [BT stopScan];
    
    [m_tvStatus setText:@"Status: Stopped !"];
    
}

-(void) onScModeChanged:(UISegmentedControl *)sender {
    if (sender.selectedSegmentIndex == 0) {
        m_vEddystoneParams.hidden = NO;
        m_bnConfigIBeacon.hidden = YES;
        [m_tvStatus setText:@"Tips: 1, Reinstall the battery of the beacon device, this will make the device going to config mode. 2, Change above parameters, then press Start button to search and config beacon."];
    } else {
        m_vEddystoneParams.hidden = YES;
        m_bnConfigIBeacon.hidden = NO;
        [m_tvStatus setText:@"Tips: Click 'Config iBeacon' button to open iBeacon configuration page."];
    }
}

-(void) onBnConfigIBeaconClicked {
    iBeaconConfigViewController *vc = [[iBeaconConfigViewController alloc] init];
    vc.mac = m_lblMac.text;
    [self.navigationController pushViewController:vc animated:YES];
}


-(void) onTagScaned: (NSString*)tagMac tag:(Tag*)tag advertisementData:(NSDictionary *)advertisementData;
{
    if ([tag._name isEqualToString:@"JW-ALARM"])
    {
        NSData* manufData = [advertisementData valueForKey:@"kCBAdvDataManufacturerData"];
        if (manufData != nil)
        {
            Byte bs[9];
            [manufData getBytes:bs length:9];
            int percent = bs[8];
            NSLog(@"Battery percent is: %d%%", percent);
        }
    }
    
    if ([tag._name isEqualToString:@"JOYWAY"])
    {
        [m_tvStatus setText:@"Status: Found a device which is ready to configure!"];
        
        [BT stopScan];

        [m_lblMac setText:tagMac];
        [BT connectTag:tagMac];
    }
}
-(void) onTagNotScaned: (NSString*)tagMac
{
//    [tvStatus setText:@"Status: not scanned!"];
}

-(void) sendConfigData
{
    EddystoneConfigParam* param = [EddystoneConfigParam alloc];
    param._uidNamespace = m_tfUID_namespace.text;
    param._uidInstance = m_tfUID_instance.text;
    param._url = m_tfURL.text;
    param._txPower = [m_tfTX_power_db.text intValue];
    param._txInterval = [m_tfTX_interval_ms.text intValue];
    param._https_or_http = TRUE;
    NSMutableArray<NSData*>* datas = [param getBytesDataListToSend];
    
    [m_tvStatus setText:@"Status: Sending parameters to device !"];
    
    for (NSData* data in datas)
    {
        [BT sendDataToTag: m_lblMac.text dataToSend:data];
        
        for (int i = 0; i < 5000*10000; i++)
        {
            // do nothing, juse waiting for configuring done.
        }
    }
    
    //start scan again after config done
    [self performSelector:@selector(onBnStartClicked) withObject:NULL afterDelay:5.0f];
}

-(void) onTagConnected: (NSString*)tagMac
{
    [m_tvStatus setText:@"Status: The device is connected!"];
    
    if (m_scMode.selectedSegmentIndex == 0) {
        [self performSelector:@selector(sendConfigData) withObject:NULL afterDelay:1.0f];
    } else {
        m_bnConfigIBeacon.enabled = YES;
    }
}
-(void) onTagDisconnected: (NSString*)tagMac
{
    [m_tvStatus setText:@"Status: The device is disconnected!"];
}
-(void) onTagData: (NSString*)tagMac data:(NSString*) data
{
    
}
-(void) onTagRssiChanged: (NSString*)tagMac rssi:(int)rssi
{
    
}



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



@end



