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

#import "MessageViewController.h"
#import "MessageItem.h"
#import "MessageDetailViewController.h"
#import "TabBarController.h"
@interface MessageViewController ()

@end

@implementation MessageViewController

- (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 pull_message :self.offset];
        
        
        dispatch_async(dispatch_get_main_queue(), ^{
            self.tableview.hidden =false;
            self.mum.hidden = true;
            if(data != nil)
            {
                self.btnrefresh.hidden = false;
                NSError *error=nil;
                NSDictionary *jsobj = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];
                int total = [[jsobj valueForKey:@"total" ] intValue] ;
                NSDictionary* objrecords = [jsobj objectForKey:@"records"];
                self.offset += total;
                for(int i=0;i<total;i++)
                {
                    
                    NSDictionary* objmsg = [objrecords objectForKey:[NSString stringWithFormat:@"record%d",i]];
                    [self.messageinfo addObject:[NSMutableDictionary dictionaryWithDictionary:objmsg]];
                    
                }
                if(total<self.limit)
                {
                    
                    int i =self.btnrefresh.state;
                    self.btnrefresh.titleLabel.text =NSLocalizedString(@"no_more", nil);
                    //                    [self.btnrefresh setTitle:@"No more" forState:UIControlStateNormal];
                }
                else
                {
                    self.btnrefresh.enabled = true;
                    self.btnrefresh.titleLabel.text =NSLocalizedString(@"load_more",nil);
                    //                    [self.btnrefresh setTitle:@"Load more" forState:UIControlStateNormal];
                }
               
                
//                [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 ];
            }
            else
            {
                self.btnrefresh.enabled = true;
                self.btnrefresh.hidden = false;
                [self.btnrefresh setTitle:NSLocalizedString(@"refresh", nil) 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)loadmore
{
    self.btnrefresh.enabled = NO;
    self.btnrefresh.titleLabel.text =NSLocalizedString(@"loading",nil);
    
    //    [self.btnrefresh setTitle:@"Loading..." forState:UIControlStateNormal];
    [self loadpage];

}
- (void)viewDidLoad
{
    [super viewDidLoad];
    [[UIApplication sharedApplication] cancelAllLocalNotifications ];
    self.offset = 0;
    self.limit = 20;
    self.messageinfo = [[NSMutableArray alloc]init];
    
    self.btnrefresh = [UIButton buttonWithType:UIButtonTypeCustom];
    //    self.btnrefresh.titleLabel.text =@"Load more";
    [self.btnrefresh setTitle:NSLocalizedString(@"load_more", nil) forState:UIControlStateNormal];
//    [self.btnrefresh.titleLabel sizeToFit];
    self.btnrefresh.titleLabel.adjustsFontSizeToFitWidth = YES;
    self.btnrefresh.hidden = true;
    [self.btnrefresh setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    self.btnrefresh.backgroundColor = [UIColor lightGrayColor];
    [self.btnrefresh addTarget:self action:@selector(loadmore) forControlEvents:UIControlEventTouchUpInside];
    self.btnrefresh.frame =CGRectMake(0.0f, 0.0f, self.tableview.bounds.size.width, 44.0f);
    self.tableview.tableFooterView = self.btnrefresh;//tableFooterView;
    [self loadpage];
    // Do any additional setup after loading the view.
}
-(void)viewWillAppear:(BOOL)animated
{
    [self.tableview reloadData];
}
- (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;
    
    
}
- (IBAction)delAllMessage:(id)sender {
    if(self.messageinfo.count<=0)
        return;
    NSString * _id =[self.messageinfo[0] valueForKey:@"id"];
    if(_id.length>0)
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            
            self.mum.hidden = false;
            
            int result = [ApexMobileNetwork delAllMessage:_id];;
            
            if(result==1)
            {
                [self.messageinfo removeAllObjects ];
                self.offset = 0;
                [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
                
                [[UIApplication sharedApplication] cancelAllLocalNotifications];
                [self loadpage];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
//                if(result==1)
//                {
////                    self.mum.hidden = true;
////                    [self.messageinfo removeAllObjects ];
////                [self.tableview reloadData];
//
////                    self.btnrefresh.hidden = true;
//                }
//                
                NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
                bool autologin =[defaults boolForKey:@"autologin"];
                if(!autologin)
                {
                    TabBarController * viewController =[self.storyboard instantiateViewControllerWithIdentifier:@"LoginTabBar"];
                    [self presentViewController:viewController animated:YES completion:^{
                        
                    }];
                }
//                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 ];
//                }
//                else
//                {
//                    self.btnrefresh.enabled = true;
//                    [self.btnrefresh setTitle:@"Load more" forState:UIControlStateNormal];
//                    
//                }
//                
                
                
                
                
            });
        });

        
    {
        
    }
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    DebugLog(@"cellForRowAtIndexPath");
    
    NSString *CellIdentifier = @"tableitemmsg";
    MessageItem *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    NSString* title =NSLocalizedString(@"new_message",nil);
    NSString* time =[self.messageinfo[indexPath.row] valueForKey:@"insert_time"];
    bool bread = [[self.messageinfo[indexPath.row] valueForKey:@"is_read"] boolValue];
    if(bread==false)
    {
        cell.backgroundColor = [UIColor colorWithRed:0.91 green:0.91 blue:0.91 alpha:1];
    }
    else
    {
        cell.backgroundColor = [UIColor whiteColor];
    }
    cell.MessageLabel.text = title;
    cell.TimeLabel.text=time;
    [cell.MessageLabel sizeToFit];
//    NSString* content = [self.data.pagedata[indexPath.row] valueForKey:@"content"];
//    NSString* base64img =[self.data.pagedata[indexPath.row] valueForKey:@"image"];
//    
//    if(base64img.length>0)
//    {
//        NSData *_decodedImageData   = [[NSData alloc] initWithBase64EncodedString:base64img options:NSDataBase64DecodingIgnoreUnknownCharacters];
//        cell.image.image = [UIImage imageWithData:_decodedImageData];
//    }
//    else
//    {
//        UIImage * img =[UIImage imageNamed:@"rect_market_news"];
//        cell.image.image = img;
//        
//    }
//    cell.title.text = title;
//    [cell.title sizeToFit];
//    
//    cell.content.text =content;
    
    //    cell.imageView.image = [UIImage imageNamed:[self.toolsinfo[indexPath.row] valueForKey:@"img"]];
    
    return cell;
    
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    MessageDetailViewController * viewController = [self.storyboard instantiateViewControllerWithIdentifier:@"MessageDetailViewController"];
    NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
    NSString* sid= [self.messageinfo[indexPath.row] valueForKey:@"s_id"];
    NSString* eid= [self.messageinfo[indexPath.row] valueForKey:@"e_id"];
    
    [params setValue:sid forKey:@"s_id"];
    [params setValue:eid forKey:@"e_id"];
    viewController.params = params;
    viewController.messagelist = self.messageinfo;
    viewController.index = indexPath.row;
    
    [self.navigationController pushViewController:viewController 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
