//
//  ViewController_SubView.m
//  Sample
//
//  Created by savin on 13. 11. 14..
//  Copyright (c) 2013년 savin. All rights reserved.
//

#import "ViewController_SubViewAddPrinter.h"

@interface ViewController_SubViewAddPrinter ()
{
    UIPopoverController*                         _popOver;
}
@end

@implementation ViewController_SubViewAddPrinter
@synthesize supportedModelList;


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

-(void) dealloc
{
    
    if(supportedModelList)
    {
        [supportedModelList release];
        supportedModelList = nil;
    }
    
    [_uiLabel_Address release];
    [_uiLabel_Port release];
    [_uiPickerModelName release];
    [_uiButtonSelectModel release];
    
    [_uiSegmentedCtrl_UseSerial release];
    [super dealloc];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
}

-(void) viewDidAppear:(BOOL)animated
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didWifiStart:) name:__NOTIFICATION_NAME_WIFI_WILL_LOOKUP_ object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didWifiDeviceList:) name:__NOTIFICATION_NAME_WIFI_FOUND_PRINTER_ object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didWifiComplete:) name:__NOTIFICATION_NAME_WIFI_LOOKUP_COMPLETE_ object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didEthernetStart:) name:__NOTIFICATION_NAME_ETHERNET_WILL_LOOKUP_ object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didEthernetDeviceList:) name:__NOTIFICATION_NAME_ETHERNET_FOUND_PRINTER_ object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didEthernetComplete:) name:__NOTIFICATION_NAME_ETHERNET_LOOKUP_COMPLETE_ object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didBTStart:) name:__NOTIFICATION_NAME_BT_WILL_LOOKUP_ object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didBTDeviceList:) name:__NOTIFICATION_NAME_BT_FOUND_PRINTER_ object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didBTComplete:) name:__NOTIFICATION_NAME_BT_LOOKUP_COMPLETE_ object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didBLEStart:) name:__NOTIFICATION_NAME_BLE_WILL_LOOKUP_ object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didBLEDeviceList:) name:__NOTIFICATION_NAME_BLE_FOUND_PRINTER_ object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didBLEComplete:) name:__NOTIFICATION_NAME_BLE_LOOKUP_COMPLETE_ object:nil];
}

// Wifi Lookup Start!!
- (void) didWifiStart:(NSNotification*)notification {
}

// Wifi Lookup Complete!!
- (void) didWifiComplete:(NSNotification*)notification {
}

- (void) didWifiDeviceList:(NSNotification*)notification
{
    UPOSPrinter* lookupDevice  = (UPOSPrinter*)[[notification userInfo] objectForKey:__NOTIFICATION_NAME_WIFI_FOUND_PRINTER_];
    if( lookupDevice == nil)
        return;
    
    _uiTextField_Address.text = lookupDevice.address;
    _uiTextField_Port.text = lookupDevice.port;
    _uiTextField_LDN.text = lookupDevice.ldn;
    [_uiButtonSelectModel setTitle:lookupDevice.modelName forState:UIControlStateNormal];
    
    if( lookupDevice.interfaceType == [NSNumber numberWithInteger:_INTERFACETYPE_WIFI] )
        _uiSegmentedCtrl_InterfaceType.selectedSegmentIndex = 0;
    else if( lookupDevice.interfaceType == [NSNumber numberWithInteger:_INTERFACETYPE_ETHERNET] )
        _uiSegmentedCtrl_InterfaceType.selectedSegmentIndex = 1;
    else if( lookupDevice.interfaceType == [NSNumber numberWithInteger:_INTERFACETYPE_BLUETOOTH] )
        _uiSegmentedCtrl_InterfaceType.selectedSegmentIndex = 2;
    else
        _uiSegmentedCtrl_InterfaceType.selectedSegmentIndex = 0;
}

// Ethernet Lookup Start!!
- (void) didEthernetStart:(NSNotification*)notification {
}

// Ethernet Lookup Complete!!
- (void) didEthernetComplete:(NSNotification*)notification {
}

- (void) didEthernetDeviceList:(NSNotification*)notification
{
    UPOSPrinter* lookupDevice  = (UPOSPrinter*)[[notification userInfo] objectForKey:__NOTIFICATION_NAME_ETHERNET_FOUND_PRINTER_];
    if( lookupDevice == nil)
        return;
    
    _uiTextField_Address.text = lookupDevice.address;
    _uiTextField_Port.text = lookupDevice.port;
    _uiTextField_LDN.text = lookupDevice.ldn;
    [_uiButtonSelectModel setTitle:@"LookupDev-Ethernet" forState:UIControlStateNormal];
    
    if( lookupDevice.interfaceType == [NSNumber numberWithInteger:_INTERFACETYPE_WIFI] )
        _uiSegmentedCtrl_InterfaceType.selectedSegmentIndex = 0;
    else if( lookupDevice.interfaceType == [NSNumber numberWithInteger:_INTERFACETYPE_ETHERNET] )
        _uiSegmentedCtrl_InterfaceType.selectedSegmentIndex = 1;
    else if( lookupDevice.interfaceType == [NSNumber numberWithInteger:_INTERFACETYPE_BLUETOOTH] )
        _uiSegmentedCtrl_InterfaceType.selectedSegmentIndex = 2;
    else
        _uiSegmentedCtrl_InterfaceType.selectedSegmentIndex = 0;
}

// BT Lookup Start!!
- (void) didBTStart:(NSNotification*)notification {
}

// BT Lookup Complete!!
- (void) didBTComplete:(NSNotification*)notification {
}

- (void) didBTDeviceList:(NSNotification*)notification {
    UPOSPrinter* lookupDevice = (UPOSPrinter*)[[notification userInfo] objectForKey:__NOTIFICATION_NAME_BT_FOUND_PRINTER_];
    if( lookupDevice == nil)
        return;
    
    if(lookupDevice.serialNumber && lookupDevice.serialNumber.length>1)
    {
        _uiTextField_Address.text = lookupDevice.serialNumber;
        [_uiSegmentedCtrl_UseSerial setSelectedSegmentIndex:1];
    }
    else{
        _uiTextField_Address.text = lookupDevice.address;
        [_uiSegmentedCtrl_UseSerial setSelectedSegmentIndex:0];
    }
    _uiTextField_Port.text = lookupDevice.port;
    _uiTextField_LDN.text = lookupDevice.ldn;
    [_uiButtonSelectModel setTitle:@"LookupDev-BT" forState:UIControlStateNormal];
    
    
    if( lookupDevice.interfaceType == [NSNumber numberWithInteger:_INTERFACETYPE_WIFI] )
        _uiSegmentedCtrl_InterfaceType.selectedSegmentIndex = 0;
    else if( lookupDevice.interfaceType == [NSNumber numberWithInteger:_INTERFACETYPE_ETHERNET] )
        _uiSegmentedCtrl_InterfaceType.selectedSegmentIndex = 1;
    else if( lookupDevice.interfaceType == [NSNumber numberWithInteger:_INTERFACETYPE_BLUETOOTH] )
        _uiSegmentedCtrl_InterfaceType.selectedSegmentIndex = 2;
    else
        _uiSegmentedCtrl_InterfaceType.selectedSegmentIndex = 0;
}


// BLE Lookup Start!!
- (void) didBLEStart:(NSNotification*)notification {
}

// BLE Lookup Complete!!
- (void) didBLEComplete:(NSNotification*)notification {
}

- (void) didBLEDeviceList:(NSNotification*)notification {
    UPOSPrinter* lookupDevice = (UPOSPrinter*)[[notification userInfo] objectForKey:__NOTIFICATION_NAME_BLE_FOUND_PRINTER_];
    if( lookupDevice == nil)
        return;
 
    dispatch_sync(dispatch_get_main_queue(), ^{
        [_uiButtonSelectModel setTitle:[NSString stringWithFormat:@"%@", lookupDevice.modelName] forState:UIControlStateNormal];
        _uiTextField_Address.text = lookupDevice.address;
        _uiSegmentedCtrl_InterfaceType.selectedSegmentIndex = 3;
    });
        
}



- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if([textField isFirstResponder])
        [textField resignFirstResponder];
    
    return YES;
}

-(void) parent:(ViewController_Printer*)viewController
{
    _parentView = viewController;
}
- (IBAction)interfaceChanged:(UISegmentedControl *)sender
{
    switch (sender.selectedSegmentIndex)
    {
        case 0:
        case 1:
            _uiLabel_Address.text = @"IP Address : ";
            _uiTextField_Port.enabled = YES;
            _uiTextField_Port.alpha = 1.0;
            _uiLabel_Port.alpha = 1.0;
            [_uiSegmentedCtrl_UseSerial setHidden:YES];
            
            [_uiLabel_Port setHidden:NO];
            [_uiTextField_Port setHidden:NO];
            break;
        case 2:
            _uiLabel_Address.text = @"MAC Address : ";
            _uiTextField_Port.enabled = NO;
            _uiTextField_Port.alpha = 0.4;
            _uiLabel_Port.alpha = 0.4;
            [_uiSegmentedCtrl_UseSerial setHidden:NO];
            [_uiSegmentedCtrl_UseSerial setSelectedSegmentIndex:0];
            
            [_uiLabel_Port setHidden:YES];
            [_uiTextField_Port setHidden:YES];
            break;
        default:
        {
            _uiLabel_Address.text = @"MAC Address : ";
            _uiTextField_Port.enabled = NO;
            _uiTextField_Port.alpha = 0.4;
            _uiLabel_Port.alpha = 0.4;
            [_uiSegmentedCtrl_UseSerial setHidden:YES];
            [_uiSegmentedCtrl_UseSerial setSelectedSegmentIndex:0];
            
            [_uiLabel_Port setHidden:YES];
            [_uiTextField_Port setHidden:YES];
            break;
        }
    }
}

- (IBAction)addressTypeChanged:(UISegmentedControl *)sender {
    if(sender.selectedSegmentIndex == 0)
        _uiLabel_Address.text = @"MAC Address : ";
    else
        _uiLabel_Address.text = @"Serial Number : ";
}

- (IBAction)selectModel:(UIButton*)sender
{
    sender.hidden = YES;
    _uiPickerModelName.delegate = self;
    _uiPickerModelName.dataSource = self;
    
    [_uiPickerModelName setShowsSelectionIndicator:YES];
    _uiPickerModelName.hidden = NO;
//    _uiButtonSelectModel.hidden = YES;
}

- (IBAction)onButton_Lookup:(id)sender {
    
    if(_uiSegmentedCtrl_InterfaceType.selectedSegmentIndex == 0)
        [_parentView lookup_Wifi];
    else if(_uiSegmentedCtrl_InterfaceType.selectedSegmentIndex == 1)
        [_parentView lookup_Ethernet];
    else if(_uiSegmentedCtrl_InterfaceType.selectedSegmentIndex == 2)
        [_parentView lookup_BT];
    else
        [_parentView lookup_BLE];
    
}




- (IBAction)onButton_Test:(UIButton *)sender {
    NSLog(@"1111");
}

-(IBAction)onButton_OK:(UIButton*)sender
{
    
    if(_uiButtonSelectModel.titleLabel.text.length )
    {
        /* 기기 정보 업데이트 */
        UPOSPrinter* newDevice = [[UPOSPrinter alloc] init];
        
        //  정보 확인해서 대입
        newDevice.modelName    = _uiButtonSelectModel.titleLabel.text;//@"SPP-R200II_2";
        newDevice.ldn          = _uiTextField_LDN.text;
        //        newDevice.devClass     = @"1234";
        
        NSInteger selectedIndex = 0;// _uiSegmentedCtrl_InterfaceType.selectedSegmentIndex;
        selectedIndex = MAX(_uiSegmentedCtrl_InterfaceType.selectedSegmentIndex<<1, MAX(_uiSegmentedCtrl_InterfaceType.selectedSegmentIndex, 1));
        
        newDevice.interfaceType= [NSNumber numberWithInteger:selectedIndex];  //[NSString stringWithFormat:@"%ld", (long)selectedIndex];//[NSString stringWithFormat: @"%d", 2^(_uiSegmentedCtrl_InterfaceType.selectedSegmentIndex) ];//@"4";
        
        if(_uiSegmentedCtrl_UseSerial.isHidden==NO && _uiSegmentedCtrl_UseSerial.selectedSegmentIndex==1)
        {
            newDevice.serialNumber      = _uiTextField_Address.text;//@"74:F0:7D:B0:02:0A";
        }
        else
        {
            newDevice.address      = _uiTextField_Address.text;//@"74:F0:7D:B0:02:0A";
        }
        newDevice.port         = _uiTextField_Port.text;//@"";
        
        NSLog(@"printer : %@(%@)", newDevice.modelName, newDevice.address );
        
            if([_parentView respondsToSelector:@selector(addPrinter:)])
            {
                [_parentView addPrinter:newDevice];
            }
         
        [newDevice release];
    }
    //    -(void) updateDevice:(UIDevice*)device;
    
    /* 창 닫기 */
    NSLog(@"Popping back to this view controller!");
    // reset UI elements etc here
    //    [self performSegueWithIdentifier: @"SegueToScene1" sender:self];
    //    [출처] [Xcode] 뒤로가기 (되돌리기, unwind segue)|작성자 에몬
    if([[super parentViewController]respondsToSelector:@selector(dismissModalViewControllerAnimated:)])
    {
        [[super parentViewController] dismissModalViewControllerAnimated:YES];
    }
    else // if([[super parentViewController]respondsToSelector:@selector(dismissModalViewControllerAnimated:completion:)])
    {
        [[super presentingViewController] dismissViewControllerAnimated:YES completion:nil];
    }
    
}




#pragma mark UIPickerView delegate methods

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    //  Item  갯수
    //    return sizeof(_models)/sizeof(_models[0]);
    return [self.supportedModelList count];
}

- (NSString *)pickerView:(UIPickerView *)pickerView
             titleForRow:(NSInteger)row
            forComponent:(NSInteger)component
{
    return [self.supportedModelList objectAtIndex:row];
}


- (void)pickerView:(UIPickerView *)pickerView
      didSelectRow:(NSInteger)row
       inComponent:(NSInteger)component
{
    
    pickerView.hidden = YES;
    [_uiButtonSelectModel setTitle:[self.supportedModelList objectAtIndex:row] forState:UIControlStateNormal];
    _uiButtonSelectModel.hidden = NO;
    [_uiButtonSelectModel setAlpha:1.0];
    
}




@end
