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

#import "NewsViewController.h"
#import "NewsDetailViewController.h"
@interface NewsViewController ()

@end

@implementation NewsViewController
- (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;
        if([self.module_name isEqualToString:@"Announcements"])
            data=[ApexMobileNetwork get_announcements:self.lastid limit:self.limit];
        else
            data=[ApexMobileNetwork get_marketnews:self.lastid limit:self.limit];
        
        
        dispatch_async(dispatch_get_main_queue(), ^{
            self.tableview.hidden =false;
            self.mum.hidden = true;
            if(data != nil)
            {
                [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 =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.tableview reloadData ];
            }
            else
            {
                self.btnrefresh.enabled = true;
                [self.btnrefresh setTitle:@"Load more" forState:UIControlStateNormal];
                
            }
            
            
            
            
            
        });
    });
}

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


- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationItem.title = self.module_name;
    self.limit = 10;
    self.data = [[NewsData alloc] init:self.limit];
    
    
    
    
    self.btnrefresh = [UIButton buttonWithType:UIButtonTypeCustom];
    //    self.btnrefresh.titleLabel.text =@"Load more";
    
    [self.btnrefresh setTitle:@"Load more" forState:UIControlStateNormal];
    self.btnrefresh.titleLabel.adjustsFontSizeToFitWidth = YES;
//    [self.btnrefresh.titleLabel sizeToFit];
    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];
}
- (void)loadmore
{
    self.btnrefresh.enabled = NO;
    self.btnrefresh.titleLabel.text =@"Loading...";
    //    [self.btnrefresh setTitle:@"Loading..." forState:UIControlStateNormal];
    [self loadpage];
    //    [SVProgressHUD showWithStatus:@"加载中..."];
    //    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    //    double delayInSeconds = 1.5;
    //    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
    //    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
    //        _rowCount += 5;
    //        [self.tableView reloadData];
    //        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    //        [SVProgressHUD showSuccessWithStatus:@"加载完成"];
    //        _bottomRefresh.frame = CGRectMake(0, 44+_rowCount*RCellHeight, 320, RCellHeight);
    //        _bottomRefresh.enabled = YES;
    //    });
}

- (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.
 }
 */
//- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
//{
////    if(section==1)
////        return 44;
////    else
//        return 200;
//}
//- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
//{
////    tableView dequeueReusableHeaderFooterViewWithIdentifier:<#(NSString *)#>
//    UITableViewHeaderFooterView *view = [[UITableViewHeaderFooterView alloc]initWithFrame:CGRectMake(0, 0, 360, 44.0)];
//    view.backgroundColor = [UIColor redColor];
////    UIView* footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 360, 44.0)];
////    UIButton* btnNextPage = [[UIButton alloc] initWithFrame:footerView.frame];
////    btnNextPage.titleLabel.text = NSLocalizedString(@"Load more", null);
////    [footerView addSubview:btnNextPage];
////    [view addSubview:footerView];
//    return view;
//}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return [self.data get_count];
    
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    DebugLog(@"cellForRowAtIndexPath");
    
    NSString *CellIdentifier = @"newsitem";
    NewsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    NSString* title = [self.data.pagedata[indexPath.row] valueForKey:@"title"];
    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
{
    
    NewsDetailViewController *viewcontroller=[self.storyboard instantiateViewControllerWithIdentifier:@"NewsDetailViewController"];
    viewcontroller.title = [self.data.pagedata[indexPath.row] valueForKey:@"title"];;
    viewcontroller.url = [self.data.pagedata[indexPath.row] valueForKey:@"url"];;
    [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
