//
//  FunctionSelectViewController.m
//  Apex Mobile
//
//  Created by Ray on 14-2-25.
//  Copyright (c) 2014年 United Software Applications, Inc. All rights reserved.
//

#import "FunctionSelectViewController.h"

@interface FunctionSelectViewController ()

@end

@implementation FunctionSelectViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
- (IBAction)onButtonClick:(UIButton *)sender {
    
    DebugLog(@"onButtonClick%@",sender.restorationIdentifier);
    //    sender.restorationIdentifier
    
    
    
    NSString *function_name;
    //= [sender currentTitle];
    
    switch (sender.tag) {
        case 101:
            function_name = @"Ocean Booking";
            break;
        case 102:
            function_name = @"Ocean B/L info.";
            break;
        case 103:
            function_name = @"Container detail";
            break;
        case 104:
            function_name = @"Download Document";
            
        default:
            break;
    }
    
    SearchViewController *searchViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"SearchViewController"];
    searchViewController.function_name = function_name;
    [self.navigationController pushViewController:searchViewController animated:YES];
    
    
}
- (BOOL)shouldAutorotate
{
    return YES;
}
- (IBAction)onToolsClick:(UIButton *)sender {
    
    ToolsPanelViewController *toolsViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"ToolsPanel"];
    toolsViewController.showNavigation = true;
    [self.navigationController pushViewController:toolsViewController animated:YES];
    
}
- (IBAction)OnDocumentClick:(UIButton *)sender {
    
    DocumentsViewController *documentsViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"DocumentsViewController"];
//    toolsViewController.showNavigation = true;
    [self.navigationController pushViewController:documentsViewController animated:YES];
}
- (IBAction)onResetClick:(UIButton *)sender {
    self.edit.text=@"";
}
- (IBAction)onHbolClick:(UIButton *)sender {
    self.radioContainer.selected = false;
    sender.selected = true;
    NSArray* array = [ApexMobileDB get_searchhistory:@"h_bol"];
    [self.autocompleteView.itemsSource put_predictions:array ];
}
- (IBAction)onContainerClick:(UIButton *)sender {
    self.radioHbol.selected = false;
    sender.selected = true;
    NSArray* array = [ApexMobileDB get_searchhistory:@"ctnr"];
    [self.autocompleteView.itemsSource put_predictions:array ];
}
- (IBAction)onSearchClick:(UIButton *)sender {
    
    
//    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"openurltest.txt" ofType:nil inDirectory:nil];
//    NSURL *url = [[NSURL alloc] initFileURLWithPath:filePath];
//    UIDocumentInteractionController *documentController =[UIDocumentInteractionController interactionControllerWithURL: url];
//    [documentController presentOptionsMenuFromRect:self.view.frame inView:self.view animated:YES];
//    
//    return;
    
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    
    [params setObject:@"dumb" forKey:@"id"];
    NSString* h_field;
    if(self.radioContainer.selected==true)
    {
        [params setObject:@"1" forKey:@"criterion_type"];
        h_field = @"ctnr";
    }
    else
    {
        [params setObject:@"0" forKey:@"criterion_type"];
    h_field = @"h_bol";
    }
    NSString * cargo_criterion = self.edit.text;
    if(cargo_criterion==nil)
        cargo_criterion=@"";
    [params setObject:cargo_criterion forKey:@"cargo_criterion"];
    
    
    [ApexMobileDB savehistory:h_field value:cargo_criterion];
    
    DetailTabBarController *detailViewController=[[DetailTabBarController alloc] init:@"Cargo Tracking" actions:[NSArray arrayWithObjects:@"Tracking",nil] params:params];
    [self.navigationController pushViewController:detailViewController animated:YES];
    
    
    /*
     
     Intent intent = new Intent();
     intent.setClass(this, DetailActivity.class);
     
     intent.putExtra("action0", );
     intent.putExtra("function_name", );
     
     intent.putExtra("cargo_criterion", cargo_criterion);
     intent.putExtra("actions_count", 1);
     intent.putExtra("_id", "dumb");
     String h_field;
     RadioGroup rg = (RadioGroup) findViewById(R.id.radioGroup1);
     if (rg.getCheckedRadioButtonId() == R.id.radio0)
     {
     intent.putExtra("criterion_type", 0);
     h_field = "hbol";
     }
     else
     {
     intent.putExtra("criterion_type", 1);
     h_field = "container_no";
     }
     String user = ApexTrackingApplication.get_user();
     
     startActivity(intent);
     */
    
    
}
- (IBAction)onExit:(UIButton *)sender {
    ApexMobileAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
    [appDelegate Logout];
    [self performSegueWithIdentifier:@"LOGIN" sender:self];

    
   // exit(0);
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    [textField resignFirstResponder];
    return YES;
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [[self view] endEditing:YES];
}

- (NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskPortrait;
}

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
    return UIInterfaceOrientationPortrait;
}

-(void)viewWillAppear:(BOOL)animated
{
    NSLog(@"App active");
    long i = [UIApplication sharedApplication].applicationIconBadgeNumber;
    if(i>0)
        self.messageButton.imageView.image = [UIImage imageNamed:@"ic_message_new"];
    else
        self.messageButton.imageView.image = [UIImage imageNamed:@"ic_message"];
    NSString* field = nil;
    if(self.radioHbol.selected ==true)
        field=@"h_bol";
    else
        field=@"ctnr";
    NSArray* array = [ApexMobileDB get_searchhistory:field] ;
    self.autocompleteView = [MyAutocompleteView autocompleteViewBindedTo:self.edit
                                                             usingSource:[[MyAutocompleteItemsSource alloc]
                                                                          initWithMinimumCharactersToTrigger:1 source:array
                                                                          ]
                                                             cellFactory:[[MyAutocompletionCellFactory alloc]
                                                                          initWithCellTextColor:[UIColor blackColor]
                                                                          fontSize:14]
//                                                            presentingIn:self
                                                              parentView:self.view];
    self.autocompleteView.topMargin = 0;
    //    self.autocompleteView.backgroundColor = [UIColor ui];
    
    self.autocompleteView.didAutocompleteWith = ^(MySuggestion* item)
    {
        NSLog(@"Autocompleted with: %@",  item.completionText);
    };
    
    NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
    bool autologin =[defaults boolForKey:@"autologin"];
    if(!autologin)
    {
        [self performSegueWithIdentifier:@"LOGIN" sender:self];
    }
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.navigationItem.leftBarButtonItem.tintColor  = [UIColor colorWithRed:0 green:0 blue:0 alpha:0];
    
    UIButton* btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(0, 0, 129, 32);
    [btn setImage:[UIImage imageNamed:@"apexlogo-2.png"] forState:UIControlStateNormal  ];
    UIBarButtonItem*   aBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
    self.navigationItem.leftBarButtonItem = aBarButtonItem;
    [self.radioContainer setImage:[UIImage imageNamed:@"unchecked_32.png"] forState:UIControlStateNormal];
    [self.radioContainer setImage:[UIImage imageNamed:@"checked_32.png"] forState:UIControlStateSelected];
    
    [self.radioHbol setImage:[UIImage imageNamed:@"unchecked_32.png"] forState:UIControlStateNormal];
    [self.radioHbol setImage:[UIImage imageNamed:@"checked_32.png"] forState:UIControlStateSelected];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(active)
                                                 name:UIApplicationDidBecomeActiveNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(active)
                                                 name:@"new notification" object:nil];
	// Do any additional setup after loading the view.
    
//    NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
//    bool autologin =[defaults boolForKey:@"autologin"];
//    if(!autologin)
//    {
//        [self performSegueWithIdentifier:@"LOGIN" sender:self];
//    }
    
}
-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self]; 
}
-(void) active
{
    NSLog(@"App active");
    long i = [UIApplication sharedApplication].applicationIconBadgeNumber;
    if(i>0)
        self.messageButton.imageView.image = [UIImage imageNamed:@"ic_message_new"];
    else
        self.messageButton.imageView.image = [UIImage imageNamed:@"ic_message"];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
