//
//  DeviceOptionViewController.m
//  AT288N_DEMO
//
//  Created by 류은주 on 2017. 8. 9..
//  Copyright © 2017년 ATID. All rights reserved.
//

#import "DeviceOptionViewController.h"
#import "SWRevealViewController.h"
#import "OptionTableViewCell.h"

@interface DeviceOptionViewController ()
{
    NSArray *devicemenuItems;
    ResultType res ;
}

@property (weak, nonatomic) IBOutlet UIBarButtonItem *menuopen;
@property (weak, nonatomic) IBOutlet UITableView *deviceOptionTableView;
@end

@implementation DeviceOptionViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
//    [AppDelegate showGlobalProgressHUDWithTitle:@"Loading..."];
    HUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
    HUD.labelText = @"Loading...";
    [self.navigationController.view addSubview:HUD];
    [HUD show:YES];
    
    appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [appDelegate.mReader setDelegate:self];
    
    if (appDelegate.mReader == nil) {
        return;
    }
    devicemenuItems = @[@"Firmware Version",@"Serial No.",@"Battery State",@"Beep",@"Auto off Time"];
    
    dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
        // Do something...
        
        SWRevealViewController *revealController = self.revealViewController;
        if(revealController)
        {
            [self.menuopen setTarget:self.revealViewController];
            [self.menuopen setAction:@selector(revealToggle:)];
            [self.view addGestureRecognizer:self.revealViewController.panGestureRecognizer];
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [AppDelegate dismissGlobalHUD];
            [HUD hide:YES];
            [HUD removeFromSuperview];
        });
    });
}
- (void) viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(BluetoothDisconnected:) name:@"BluetoothDisconnected" object:nil];
}
- (void) viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"BluetoothDisconnected" object:nil];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    
}
#pragma mark - Storyboard Segue
-(IBAction)prepareForUnwind:(UIStoryboardSegue *)segue {
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
           return devicemenuItems.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
         NSString *CellIdentifier = [devicemenuItems objectAtIndex:indexPath.row];
         OptionTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DeviceOptionCell" forIndexPath:indexPath];
         
         cell.memuname.text = CellIdentifier;
         if(indexPath.row == 0){
             cell.menuvalue.text = appDelegate.mReader.firmwareVersion;
         }else if(indexPath.row == 1){
             cell.menuvalue.text = appDelegate.mReader.serialNumber;
             NSLog(@"appDelegate.mReader.serialNumber %@",appDelegate.mReader.serialNumber);
         }else if (indexPath.row == 2){
             BOOL lowbattery = appDelegate.mReader.lowBatteryState;
             if(lowbattery == 0){
              cell.menuvalue.text = @"High";
             }else {
               cell.menuvalue.text = @"Low";
             }
         }else if(indexPath.row == 3){
             BOOL buzz = appDelegate.mReader.buzzer;
             if(buzz == 0){
                 cell.menuvalue.text = @"OFF";
             }else {
                 cell.menuvalue.text = @"ON";
             }
         }else if(indexPath.row == 4){
             cell.menuvalue.text = [NSString stringWithFormat:@"%d min",appDelegate.mReader.autoOffTime];
         }
         return cell;
}
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewCellEditingStyleDelete;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    if(indexPath.row == 3){
        BOOL buzz = appDelegate.mReader.buzzer;
        if(buzz == 0){
            appDelegate.mReader.buzzer = 1;
        }else {
            appDelegate.mReader.buzzer = 0;
        }
    }else if(indexPath.row == 4){
        [self autoofftimesetting];
    }
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.deviceOptionTableView reloadData];
    });
}
#pragma mark - UITextFieldDelegate
-(BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    int textvalue = [textField.text intValue];
    if((textvalue < 20) && (textvalue > 0)){
        return NO;
    }    
    textField.text = [NSString stringWithFormat:@"%d",textvalue];
    return NO;
}
#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        NSString *autotime = [alertView textFieldAtIndex:0].text;
        appDelegate.mReader.autoOffTime = [autotime integerValue];
        [self.deviceOptionTableView reloadData];
    }

}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
        return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
    } else {
        return YES;
    }
}

- (void)autoofftimesetting {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Auto Off Time:" message:@"Please enter auto off time.(min)" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:nil];
    
    alert.alertViewStyle = UIAlertViewStylePlainTextInput;
    [alert textFieldAtIndex:0].keyboardType = UIKeyboardTypeNumberPad;
    
    [alert addButtonWithTitle:@"OK"];
    [alert show];
}

#pragma mark - NSNotification
- (void)BluetoothDisconnected:(NSNotification *)notification {
    dispatch_async(dispatch_get_main_queue(), ^{
        NSLog(@"BluetoohDisconnected");
        //[self.navigationController popToRootViewControllerAnimated:YES];
        [self performSegueWithIdentifier:@"RegistDevice" sender:nil];
    });
}

@end
