#import "NetworkSettingController.h"
#import "Utils.h"
#import "System.h"
#import <ASR033WSDK/ASR033WSDK.h>
#import <SVProgressHUD/SVProgressHUD.h>
@interface NetworkSettingController ()<ASR033WDelegate>
{
    NSArray *arryDeviceInfo;
    UIAlertController *alert;
    ASR033W *asr033w;
    NSString *ipString;
}
@property (weak, nonatomic) IBOutlet UIView *viewStatic;
@property (weak, nonatomic) IBOutlet UITextField *txtFieldIP;
@property (weak, nonatomic) IBOutlet UITextField *txtFieldSubnet;
@property (weak, nonatomic) IBOutlet UITextField *txtFieldGateWay;
@property (weak, nonatomic) IBOutlet UIButton *searchAgainButton;
@property (weak, nonatomic) IBOutlet UISegmentedControl *segmentDHCPStatic;
-(IBAction)searchButtonAction:(id)sender;
-(IBAction)doneButtonAction:(id)sender;
-(IBAction)segmentButtonAction:(id)sender;
@end

@implementation NetworkSettingController

//----------------------------------------------
#pragma mark - Lifecycle
//----------------------------------------------
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    asr033w = [ASR033W sharedInstance];
    asr033w.delegate = self;
    [self searchDevice];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    ipString = @"";
    arryDeviceInfo = [[NSArray alloc] init];
}

//----------------------------------------------
#pragma mark - IBAction
//----------------------------------------------
-(IBAction)searchButtonAction:(id)sender
{
    [self searchDevice];
}

-(IBAction)doneButtonAction:(id)sender
{
    [self.view endEditing:YES];
    if (![self isIPAddress:self.txtFieldIP.text IP:YES]) {
        [Utils showAlert:@"Error" message:@"IP is wrong."];
        return;
    }
    if (![self isIPAddress:self.txtFieldSubnet.text IP:NO]) {
        [Utils showAlert:@"Error" message:@"Subnet mask is wrong."];
        return;
    }
    if (![self isIPAddress:self.txtFieldGateWay.text IP:NO]) {
        [Utils showAlert:@"Error" message:@"Gateway is wrong."];
        return;
    }
    [SVProgressHUD show];
    [asr033w connectServerWithIP:ipString remoteport:9600];
}

-(IBAction)segmentButtonAction:(id)sender
{
    int selectIndex  =  (int)[self.segmentDHCPStatic selectedSegmentIndex];
    //DHCP
    if(selectIndex == 0) {
        [self enableTextField:NO];
    }
    
    //Static IP
    else if(selectIndex == 1){
        [self enableTextField:YES];
    }
}

//----------------------------------------------
#pragma mark - PrivateMethod
//----------------------------------------------
- (BOOL)isIPAddress:(NSString *)ipStr IP:(BOOL)ip{
    if (ipStr == nil || [@"" isEqualToString:ipStr]) {
        return NO;
    }
    if (ip) {
        NSString *string = @"(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)\\.(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)\\.(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)\\.(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)";
        NSPredicate * predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", string];
        BOOL ips = [predicate evaluateWithObject:ipStr];
        return ips;
    } else {
        NSArray *ipArray = [ipStr componentsSeparatedByString:@"."];
        if (ipArray.count == 4) {
            for (NSString *ipnumberStr in ipArray) {
                int ipnumber = [ipnumberStr intValue];
                if (!(ipnumber >= 0 && ipnumber <= 255)) {
                    return NO;
                }
            }
            return YES;
        }
        return NO;
    }
}

- (void)searchDevice
{
    [SVProgressHUD showWithStatus:@"Searching Device"];
    [asr033w startSearchDevice];
}

- (void)enableTextField:(BOOL)isOn
{
    [self.txtFieldIP setEnabled:isOn];
    [self.txtFieldSubnet setEnabled:isOn];
    [self.txtFieldGateWay setEnabled:isOn];
}

- (void)showAlertViewAllDevics
{
    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"Found Device"
                                                                   message:@"Please select device IP"
                                                            preferredStyle:UIAlertControllerStyleActionSheet];
    
    for(int i=0; i<[arryDeviceInfo count]; i++)
    {
        NSDictionary *device = [arryDeviceInfo objectAtIndex:i];
        NSLog(@"device = %@", device);
        if (device.count == 0) {
            continue;
        }
        NSString *sIp = [device objectForKey:SEARCH_HOST_SERVER_IP] ?:@"";
        
        if (sIp && ![@"" isEqualToString:sIp]) {
            UIAlertAction* ip = [UIAlertAction actionWithTitle:sIp
                                                         style:UIAlertActionStyleDefault
                                                       handler:^(UIAlertAction * action) {
                NSDictionary *device = [self->arryDeviceInfo objectAtIndex:i];
                ipString = [device objectForKey:SEARCH_HOST_SERVER_IP];
                [self.txtFieldIP setText:[device objectForKey:SEARCH_HOST_SERVER_IP]];
                [self.txtFieldSubnet setText:[device objectForKey:SEARCH_MASK]];
                [self.txtFieldGateWay setText:[device objectForKey:SEARCH_GATEWAY]];
                NSString *mode = [device objectForKey:SEARCH_DHCP_SW];
                NSLog(@"mode = %@", mode);
                if  ([mode isEqualToString:@"dhcp"])
                {
                    [self.segmentDHCPStatic setSelectedSegmentIndex:0];
                    [self enableTextField:NO];
                }
                else
                {
                    [self.segmentDHCPStatic setSelectedSegmentIndex:1];
                    [self enableTextField:YES];
                }
            }];
            [alert addAction:ip];
        }
        
    }
    
    UIAlertAction* cancel = [UIAlertAction actionWithTitle:@"Cancel"
                                                     style:UIAlertActionStyleDefault
                                                   handler:nil];
    [alert addAction:cancel];

    alert.popoverPresentationController.sourceRect = self.searchAgainButton.frame;
    alert.popoverPresentationController.sourceView = self.view;
    [self presentViewController:alert animated:YES completion:nil];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}
//----------------------------------------------
#pragma mark - ASR033WDelegate
//----------------------------------------------
- (void)receivedASR033WSearchDeviceInfo:(NSArray *)arrInfos {
    [SVProgressHUD dismiss];
    self->arryDeviceInfo = arrInfos;
    [self showAlertViewAllDevics];
}
- (void)receivedASR033WNetworkState:(ASR033WNetworkState)state error:(NSError *)error {
    switch (state) {
        case ASR033WNetworkStateError:{
            [self alertViewStatus];
        }
            break;
        case ASR033WNetworkStateConnected:{
            [self setIP];
        }
            break;
        default:{
            
        }
            break;
    }
}
- (void)setIP {
    dispatch_async(dispatch_get_main_queue(),^{
        [self->asr033w startReceiveRFIDData];
        int selectIndex  =  (int)[self.segmentDHCPStatic selectedSegmentIndex];
        NSString *ip = self.txtFieldIP.text;
        NSString *sub = self.txtFieldSubnet.text;
        NSString *gw  = self.txtFieldGateWay.text;
        if (selectIndex == 0) {
            //DHCP
            [self->asr033w setIPStatus:ASR033WIPStatus_DHCP IP:@"" Subnet:@"" Gateway:@""];
        } else if(selectIndex == 1) {
            //Static IP
            [self->asr033w setIPStatus:ASR033WIPStatus_STATIC IP:ip Subnet:sub Gateway:gw];
        }
        [self->asr033w disconnectServer];
        [self performSelector:@selector(finshSetID) withObject:nil afterDelay:10];
    });
}
- (void)finshSetID{
    dispatch_async(dispatch_get_main_queue(),^{
        [SVProgressHUD dismiss];
        [Utils showAlert:@"Confirm" message:@"The network has changed.Press the [Search again] button and check the changed information."];
    });
}
- (void)alertViewStatus{
    dispatch_async(dispatch_get_main_queue(),^{
        [SVProgressHUD dismiss];
        if (self->alert) {
            [self->alert dismissViewControllerAnimated:YES completion:nil];
            self->alert = nil;
        }
        self->alert = [UIAlertController alertControllerWithTitle:@"Network"
                                                    message:@"Fail Connected!"
                                             preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *ok = [UIAlertAction
                             actionWithTitle:@"OK"
                             style:UIAlertActionStyleDefault
                             handler:nil];
        
        [self->alert addAction:ok];
        [self presentViewController:self->alert animated:YES completion:nil];
    });
}
@end
