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

#import "MessageDetailViewController.h"
#import "MessageDetailItem.h"
#import "ApexMobileNetwork.h"
#import "RTLabel.h"
#import "DetailTabBarController.h"
#import "TabBarController.h"
#define  DEF_CELL_HEIGHT 44
#define  DEF_TABLE_HEIGHT 44
#define  LINE_WIDTH 0
#define  CELL_MARGIN 0
#define  LABEL_MARGIN 5

@interface MessageDetailViewController ()

@end

@implementation MessageDetailViewController

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

- (NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskPortrait;
}

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
    return UIInterfaceOrientationPortrait;
}
-(void) loadpage
{
    
    //    [self.params setValue:[NSString stringWithFormat:@"%ld",self.offset] forKey:@"offset"];
    self.mum.center = self.view.center;
    //    self.btnrefresh.enabled = false;
    //
    //    NSTimeInterval animationDuration = 0.30f;
    //    [UIView beginAnimations:@"ResizeView" context:nil];
    //    [UIView setAnimationDuration:animationDuration];
    //    self.prepageButton.enabled=false;
    //    self.nextpageButton.enabled=false;
    //    self.mum.hidden = false;
    //    self.grid.hidden = true;
    //    self.mum.hidden = false;
    //    self.tableview.hidden = true;
    
    //    [UIView commitAnimations];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        
        NSData* data=nil;
        data=[ApexMobileNetwork get_MessageDetail:self.offset limit:self.limit from:self.s_id to:self.e_id];
        
        
        dispatch_async(dispatch_get_main_queue(), ^{
            self.tableview.hidden =false;
            self.mum.hidden = true;
            if(data != nil)
            {
                NSError *error=nil;
                NSDictionary *jsobj = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];
                int total = [[jsobj valueForKey:@"total" ] intValue] ;
                NSDictionary* objrecords = [jsobj objectForKey:@"records"];
                
                for(int i=0;i<total;i++)
                {
                    
                    NSDictionary* objmsg = [objrecords objectForKey:[NSString stringWithFormat:@"record%d",i]];
                    [self.messageinfo addObject:objmsg];
                    
                }
                
                
                //                [self.data appenddata: data];
                //                self.lastid = self.data._id;
                //                self.btnrefresh.hidden = false;
                //                if(self.data.finishload==true)
                //                {
                //
                //                    int i =self.btnrefresh.state;
                //                    self.btnrefresh.titleLabel.text =@"No more";
                //                    //                    [self.btnrefresh setTitle:@"No more" forState:UIControlStateNormal];
                //                }
                //                else
                //                {
                //                    self.btnrefresh.enabled = true;
                //                    self.btnrefresh.titleLabel.text =@"Load more";
                //                    //                    [self.btnrefresh setTitle:@"Load more" forState:UIControlStateNormal];
                //                }
                [self.tableview reloadData ];
                [UIApplication sharedApplication].applicationIconBadgeNumber --;
                NSMutableDictionary * item = self.messagelist[self.index];
                [item setValue:@"t" forKey:@"is_read"];
                
//                [self.messagelist[self.index] setValue:@"0" forKey:@"is_read"];
            }
            else
            {
                //                self.btnrefresh.enabled = true;
                //                [self.btnrefresh setTitle:@"Load more" forState:UIControlStateNormal];
                
            }
            NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
            bool autologin =[defaults boolForKey:@"autologin"];
            if(!autologin)
            {
                TabBarController * viewController =[self.storyboard instantiateViewControllerWithIdentifier:@"LoginTabBar"];
                [self presentViewController:viewController animated:YES completion:^{
                    
                }];
            }
            
            
            
            
            
        });
    });
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.offset = 0;
    self.limit = 20;
    self.s_id = [self.params valueForKey:@"s_id"];
    self.e_id = [self.params valueForKey:@"e_id"];
    self.messageinfo = [[NSMutableArray alloc]init];
    [self loadpage];
    // Do any additional setup after loading the view.
}
//-(void) viewWillAppear:(BOOL)animated
//{
//    NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
//    bool autologin =[defaults boolForKey:@"autologin"];
//    if(!autologin)
//    {
//        TabBarController * viewController =[self.storyboard instantiateViewControllerWithIdentifier:@"LoginTabBar"];
//        [self presentViewController:viewController animated:YES completion:^{
//            
//        }];
//    }
//}

- (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 self.messageinfo.count;
    
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    DebugLog(@"cellForRowAtIndexPath");
    
    //    NSString *CellIdentifier = @"messagedetailitem";
    //    MessageDetailItem *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    NSString *CellIdentifier = @"messagedetailitem";
    MessageDetailItem *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    
    NSString* title = [self.messageinfo[indexPath.row] valueForKey:@"title"];
    cell.contentLabel.text = title;
    
   
    
    return cell;
    
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    
    [params setObject:@"dumb" forKey:@"id"];
    
    [params setObject:@"1" forKey:@"criterion_type"];
    NSString * cargo_criterion = [self.messageinfo[indexPath.row] valueForKey:@"url"];
    
    [params setObject:cargo_criterion forKey:@"cargo_criterion"];
    
    
    DetailTabBarController *detailViewController=[[DetailTabBarController alloc] init:@"Cargo Tracking" actions:[NSArray arrayWithObjects:@"Tracking",nil] params:params];
    [self.navigationController pushViewController:detailViewController animated:YES];
    
    //    SearchViewController *searchViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"SearchViewController"];
    //    searchViewController.function_name = @"Download Document";
    //    [self.navigationController pushViewController:searchViewController animated:YES];
    //    return;
    
    //    NSString* title = [self.toolsinfo[indexPath.row] valueForKey:@"title"];
    //    if([title isEqualToString:@"Market news"])
    //    {
    //        NewsViewController *newsview=[[NewsViewController alloc] init:title ];
    //        [self.navigationController pushViewController:newsview animated:YES];
    //    }
    //    else if([title isEqualToString:@"Announcements"])
    //    {
    //        NewsViewController *newsview=[[NewsViewController alloc] init:title ];
    //        [self.navigationController pushViewController:newsview animated:YES];
    //    }
}

@end
