//
//  dList.m
//  Caravan
//
//  Created by Claus Richter on 11/19/15.
//
//

#import "dList.h"

#import "ViewController.h"



@interface dList ()

@end

float flagReturnKeyPressed =0;
float flagItemNotInTheList = 0;
float dListPagevisit = 0;
int flagItemFiltered = 0;
int alertFlag2 = 0;
int flagImportFixedWing = 1;

@implementation dList{
    
    ViewController* mainControllerClass_;
    
}

- (void)didMoveToParentViewController:(UIViewController *)parent {
    [super didMoveToParentViewController:parent];
    
    
}

/*
- (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse {
    return nil;
}

 */

- (void) importWaypoints {
    
    NSURL *URL;
    
        if (flagImportFixedWing == 1) {
            
        URL = [NSURL URLWithString: @"http://www.gyronimosystems.com/TropicAir/Tropic_Waypoints_FixedWing.txt"];
        }else{
            
        URL = [NSURL URLWithString: @"http://www.gyronimosystems.com/TropicAir/Tropic_Waypoints_Helicopter.txt"];
        }
    
    
    
    [[NSURLCache sharedURLCache] removeAllCachedResponses];
    [[NSURLCache sharedURLCache] setDiskCapacity:0];
    [[NSURLCache sharedURLCache] setMemoryCapacity:0];
    
    /*
     NSURLRequest *request = [NSURLRequest requestWithURL:URL
     cachePolicy:NSURLRequestReloadIgnoringCacheData
     timeoutInterval:60.0];
     
     NSURLConnection *connection = [NSURLConnection connectionWithRequest:request
     delegate:self];
     */
    
    NSStringEncoding encoding;
    NSError *error;
    
    NSString *importedText = [NSString stringWithContentsOfURL:URL usedEncoding:&encoding error:&error];
    
    //NSLog( @"importedText %@", importedText);
    
    importedText  = [ importedText stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    
    
    NSArray* componentItems  = [importedText componentsSeparatedByString:@","];
    
    //NSLog( @"componentItems %@", componentItems);
    
    
    [array1 removeAllObjects];
    
    for (int i=0; i < componentItems.count; ++i) {
        
         [array1 addObject: [componentItems objectAtIndex:i]   ];
        
    }
    
    NSUserDefaults *defaults  = [NSUserDefaults standardUserDefaults];
    [defaults  setObject:array1      forKey:[@"1" stringByAppendingString:@"_"]];

    
    //NSLog( @"array1 %@", array1);
    
    
    [self FlightLogCreateLabels];
    
    
}



- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    
    _viewNotInTheListMessage.hidden= YES;
   
    
     mainControllerClass_ = [[ViewController alloc] init];
    
     _importButton.hidden = YES;
    
    
    array1 = [[NSMutableArray alloc] init];


    
     [_scrollViewLabels setScrollEnabled:YES];
    
     [_scrollViewLabels setContentSize:CGSizeMake(_scrollViewLabels.frame.size.width, _viewLabels.frame.size.height)];

  

    
    
    NSUserDefaults *defaults  = [NSUserDefaults standardUserDefaults];
    
    dListPagevisit = [defaults  floatForKey: @"MBpagevisit"];

    
    
    if (dListPagevisit < 1) { // wirklich
        
        
        [defaults  setFloat: 100        forKey: @"dListPagevisit"];
        
       
        
        
        [array1 addObject:@"Location A"];
        
        [array1 addObject:@"Location B"];
        
        [array1 addObject:@"Location C"];
        
        [defaults  setObject:array1      forKey:[@"1" stringByAppendingString:@"_"]];
        
        
    }else{
        
        // second load
        
        
       NSMutableArray *arrayName1Load = [[[NSUserDefaults standardUserDefaults] objectForKey:[@"1" stringByAppendingString:@"_"]] mutableCopy];
        
        
        [array1 setArray:arrayName1Load];

        
      }

    

    
    [self FlightLogCreateLabels];
    
}

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


-(void) initializeDlistWindow {
    
    ViewController *parent = (ViewController *)self.parentViewController;
    int count = [parent .arrayName23 count];
    //NSLog(@"count %d ", count);
    if (count > 40) {
        //NSLog(@"[parent .arrayName23 objectAtIndex:44] %@ ", [parent .arrayName23 objectAtIndex:44]);
        if ([[parent .arrayName23 objectAtIndex:44] isEqualToString:@"YES"]) {
            _importButton.hidden = NO;
        }else{
            _importButton.hidden = YES;
        }
        
        
        
    }else{
        _importButton.hidden = YES;
    }
    
}

- (void) FlightLogCreateLabels {
    
   
    
    
    
    for(UIView *subview in [_viewLabels subviews]) {
        [subview removeFromSuperview];
    }
    
    float xPos1 = 10;
    
    float yGap = 50;
    
 
   
    
    [_scrollViewLabels setContentSize:CGSizeMake(_scrollViewLabels.frame.size.width, array1.count * 55)];
    
    
    for (int i=0; i < array1.count; ++i) {
                


        
        
        
        // item text
        
        UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(xPos1 +20, 18 + ((i)*yGap), 200, 30)];
        textField.borderStyle = UITextBorderStyleRoundedRect;
        textField.minimumFontSize = 5;
        textField.font = [UIFont boldSystemFontOfSize:17];
        textField.autocorrectionType = UITextAutocorrectionTypeNo;
        textField.clearButtonMode = UITextFieldViewModeWhileEditing;
        textField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
        textField.keyboardType = UIKeyboardTypeDefault;
        textField.returnKeyType = UIReturnKeyDefault;
        textField.adjustsFontSizeToFitWidth= NO;
        textField.autocapitalizationType = UITextAutocapitalizationTypeAllCharacters;
        textField.textAlignment = NSTextAlignmentLeft;
        textField.enabled = NO;
        textField.backgroundColor = [UIColor darkGrayColor];
        textField.textColor = [UIColor whiteColor];
        
        [textField addTarget:self
                  action:@selector(closeKeyboardDlist:)
        forControlEvents:UIControlEventEditingDidEnd];

        
        
        [textField  setText: [array1 objectAtIndex: i ] ];
        
        textField.tag = i+1000;
        
        [_viewLabels addSubview: textField];

        
       
        // delete button
        
        if (array1.count > 0) {
        
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(xPos1 + 55+200+50, 18 + ((i)*yGap) - 3, 40, 40);
        
        [btn addTarget:self
                action:@selector(actionDelete:)
      forControlEvents:UIControlEventTouchUpInside];
     
        btn.tag = i+3000;
        
        btn.hidden = NO;
        
        btn.backgroundColor = [UIColor clearColor];
        [btn  setBackgroundImage:[UIImage imageNamed: @"button minus red.png" ] forState:UIControlStateNormal];
        
       
        
        [_viewLabels addSubview:btn];
        
        }
        
        
        // select button
        
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(xPos1 + 20, 18 + ((i)*yGap), 200, 30);
        
        [btn addTarget:self
                action:@selector(actionSelectTextField:)
      forControlEvents:UIControlEventTouchUpInside];
        
        btn.tag = i+2000;
        
        btn.backgroundColor = [UIColor clearColor];
        
        [_viewLabels addSubview:btn];
        
        
        
        
        

        
        
        
    }
    
    
    // save array
    
     NSUserDefaults *defaults  = [NSUserDefaults standardUserDefaults];
    
    [defaults  setObject:array1      forKey:[@"1" stringByAppendingString:@"_"]];
   
    
    
    
}

- (void) FlightLogCreateLabelsFromFilteredArray {
    
    for(UIView *subview in [_viewLabels subviews]) {
        [subview removeFromSuperview];
    }
    
    float xPos1 = 10;
    
    float yGap = 50;
    
    
    
    for (int i=0; i < filteredItems.count; ++i) {
        
        
        
        
        
        
        
        // item text
        
        UITextField * textField = [[UITextField alloc] initWithFrame:CGRectMake(xPos1 + 20, 18 + ((i)*yGap), 200, 30)];
        textField.borderStyle = UITextBorderStyleRoundedRect;
        textField.minimumFontSize = 5;
        textField.font = [UIFont boldSystemFontOfSize:17];
        textField.autocorrectionType = UITextAutocorrectionTypeNo;
        textField.clearButtonMode = UITextFieldViewModeWhileEditing;
        textField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
        textField.keyboardType = UIKeyboardTypeDefault;
        textField.returnKeyType = UIReturnKeyDefault;
        textField.adjustsFontSizeToFitWidth= NO;
        textField.textAlignment = NSTextAlignmentLeft;
        textField.enabled = NO;
        textField.backgroundColor = [UIColor darkGrayColor];
        textField.textColor = [UIColor whiteColor];
        
        
        
        [textField  setText: [filteredItems objectAtIndex: i ] ];
        
        textField.tag = i+1000;
        
        [_viewLabels addSubview: textField];
        
        
        
        // delete button
        
        if (filteredItems.count > 1) {
            
       
        
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(xPos1 + 55+200+50, 18 + ((i)*yGap) - 3, 40, 40);
        
        [btn addTarget:self
                action:@selector(actionDelete:)
      forControlEvents:UIControlEventTouchUpInside];
        
        btn.tag = i+3000;
        
        btn.hidden = YES;
        
        btn.backgroundColor = [UIColor clearColor];
        [btn  setBackgroundImage:[UIImage imageNamed: @"button minus red.png" ] forState:UIControlStateNormal];
            
        
        [_viewLabels addSubview:btn];
        
        }
        
        
        // select button
        
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(xPos1 + 20, 18 + ((i)*yGap), 200, 30);
        
        [btn addTarget:self
                action:@selector(actionSelectTextField:)
      forControlEvents:UIControlEventTouchUpInside];
        
        btn.tag = i+2000;
        
        btn.backgroundColor = [UIColor clearColor];
        
        [_viewLabels addSubview:btn];
        
        
        
        
        
        
        
    }
    
    
    
    
    
    
}


- (void)actionSelectTextField:(UIButton*)sender {
    
     //NSLog(@"actionSelectTextField ");
    
     //NSLog(@"flagItemFiltered   %d", flagItemFiltered);

    
   
    
    
    
    float itemNr = 0;
    
    for (int i=0; i < array1.count; ++i) {
        
        itemNr = i + 1000;
        
        // set label to normal
        UITextField* field = (UITextField*)[_viewLabels viewWithTag: itemNr];
        field.enabled = NO;
        field.backgroundColor = [UIColor darkGrayColor];
        field.textColor = [UIColor whiteColor];
    }
    
    
    
    
    // set label to selected
    itemNr = sender.tag -1000;
    
     //NSLog(@"itemNr   %.0f", itemNr);
   
    
    UITextField* field = (UITextField*)[_viewLabels viewWithTag: itemNr];
    field.enabled = YES;
    field.backgroundColor = [UIColor whiteColor];
    field.textColor = [UIColor blackColor];
    
    
    field = (UITextField*)[_viewLabels viewWithTag: itemNr];   

    NSString *fieldText = [field text];
    _inputTextDlist.text = fieldText;
    
    //NSLog(@"setObject  _inputTextDlist.text %@", _inputTextDlist.text);
    
    NSString *merker = _inputTextDlist.text;
    
    _viewNotInTheListMessage.hidden = YES;
    
    
    
    // select and set
    
    
   
    
    
    [self FlightLogCreateLabels];
    

    
    
    _viewNotInTheListMessage.hidden = YES;
    
    [self.view endEditing:TRUE];
    
    NSUserDefaults *defaults  = [NSUserDefaults standardUserDefaults];
    
    
    [defaults  setObject: _inputTextDlist.text        forKey:@"dListInputText"];
    
    
    if (flagItemFiltered == 1) {
        [defaults  setObject: merker        forKey:@"dListInputText"];
    }
    
    
    _inputTextDlist.text =@"";
    
    
    ViewController *parent = (ViewController *)self.parentViewController;
    
    [parent dListSetInputField];

    
    
  
}

- (void)ClearField {
    
    
        
    _viewNotInTheListMessage.hidden = YES;
    
    [self.view endEditing:TRUE];
    
    NSUserDefaults *defaults  = [NSUserDefaults standardUserDefaults];
    
    
    [defaults  setObject: _inputTextDlist.text        forKey:@"dListInputText"];
    
    _inputTextDlist.text =@"";
    
    ViewController *parent = (ViewController *)self.parentViewController;
    
    [parent dListSetInputField];
    
    
    
    
}

- (IBAction)actionClearField:(id)sender {
    
    [self ClearField];

}


- (IBAction)actionCancel:(id)sender {
    
    
    ViewController *parent = (ViewController *)self.parentViewController;

    [parent dListCancel];
    
}




- (IBAction)actionImportData:(id)sender {
    
    
    alertFlag2 = 1;
    
    
    UIAlertView *alert = [[UIAlertView alloc]
                          
                          initWithTitle:@"Import Location Data"
                          
                          message:@"Do you want to import and overwrite locations?"
                          
                          delegate:self
                          
                          cancelButtonTitle:@"CANCEL"
                          
                          
                          
                          otherButtonTitles:@"Fixed Wing", @"Helicopter", nil];
    
    [alert show];
    
    
    
}



-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    
    if (alertFlag2 == 1) {
        
        if (buttonIndex == 0) {
          
            
        }
        
        
        if (buttonIndex == 1) {
            
            //NSLog (@"flagImport FixedWing 1");
            
            flagImportFixedWing = 1;
            
            [self importWaypoints];
         
        }
        
        
        
        if (buttonIndex == 2) {
            
            //NSLog (@"flagImport FixedWing 0");
            
            flagImportFixedWing = 0;
            
            [self importWaypoints];



            
            
        }
        
    }
    

    
}





- (void)actionDelete:(UIButton*)sender {
    
    float itemNr = sender.tag;
    
    if ( array1.count >0) {
       
   
    
    [array1 removeObjectAtIndex:itemNr-3000];
    
    [self FlightLogCreateLabels];
    
        
    }
    
}










- (IBAction)actionSortAtoZ:(id)sender {
    
    NSArray *sortedArray = [array1  sortedArrayUsingComparator:
                            ^NSComparisonResult(id obj1, id obj2){
                                //descending order
                                return [obj2 compare:obj1];
                                //ascending order
                                //return [obj1 compare:obj2];
                            }];
    //NSLog(@"A to Z %@", sortedArray);
    
    
     for (int i=0; i < array1.count; ++i) {
         
         
         [array1 replaceObjectAtIndex:i withObject: [sortedArray objectAtIndex: i ] ];

         
         
     }
    
     [self FlightLogCreateLabels];
    
    
}

- (IBAction)actionSortZtoA:(id)sender {
    
    
    
    //NSArray *temp = [[NSArray alloc] initWithObjects:@"b", @"c", @"5", @"d", @"85", nil];
    
    NSArray *sortedArray = [array1  sortedArrayUsingComparator:
                            ^NSComparisonResult(id obj1, id obj2){
                                //descending order
                                //return [obj2 compare:obj1];
                                //ascending order
                                return [obj1 compare:obj2];
                            }];
    //NSLog(@"Z to A %@", sortedArray);
    
    for (int i=0; i < array1.count; ++i) {
        
        
        [array1 replaceObjectAtIndex:i withObject: [sortedArray objectAtIndex: i ] ];
        
        
        
    }
    
    [self FlightLogCreateLabels];

    
    
    
}

- (void) activateTextfield {
    
   //[self.inputTextDlist becomeFirstResponder];
    
    flagReturnKeyPressed = 0;
    
    //NSLog(@"activateTextfield");
    
    return;
    
}




- (IBAction)closeKeyboardDlist:(id)sender {
    
    //NSLog(@"closeKeyboardDlist");

    
    
    [self FlightLogCreateLabels];
    
    
    
    
    
    
    flagReturnKeyPressed = flagReturnKeyPressed +1;
    
    if (flagReturnKeyPressed == 1) {
        
        if (flagItemNotInTheList == 1) {
            
            
            // add entry
            [array1 addObject: _inputTextDlist.text];
            
           
        }

        
        
        
        
     
     
        
        [self FlightLogCreateLabels];
        

       
            
          _viewNotInTheListMessage.hidden = YES;
        
        [self.view endEditing:TRUE];
        
        NSUserDefaults *defaults  = [NSUserDefaults standardUserDefaults];
        
        
        [defaults  setObject: _inputTextDlist.text        forKey:@"dListInputText"];
        
        _inputTextDlist.text =@"";
        
        ViewController *parent = (ViewController *)self.parentViewController;
        
        [parent dListSetInputField];

    }
    
   
    
}








- (IBAction)enterFieldValueChanged:(id)sender {
    
    
    //NSLog(@"enterFieldValueChanged _inputTextDlist.text %@", _inputTextDlist.text);
    
    flagItemFiltered = 0;

    
    NSString *firstLetter = _inputTextDlist.text;
    
    if ([firstLetter isEqualToString:@""]) {
        
        [self FlightLogCreateLabels];
        
        
        _viewNotInTheListMessage.hidden = YES;

       
        
        
    }else{
        
        
        NSPredicate *sPredicate = [NSPredicate predicateWithFormat:@"SELF beginswith[c] %@", firstLetter ];
        filteredItems = [array1 filteredArrayUsingPredicate:sPredicate];
        
        
         //NSLog(@"filteredItems %@", filteredItems);
        
        flagItemFiltered = 1;
        
        _viewNotInTheListMessage.hidden = YES;
        
        flagItemNotInTheList = 0;
        
        if (filteredItems.count < 1) {
            
            _viewNotInTheListMessage.hidden = NO;
            
            _labelNotInTheList.text = firstLetter;
            
            flagItemNotInTheList = 1;

        }
        
        
        
        
        [self FlightLogCreateLabelsFromFilteredArray];
        
        
    }
    
  
    

    
    
}






@end
