//
//  HistoryView.m
//  SKCore
//
//  Created by jungeol.park on 2014. 10. 1..
//  Copyright (c) 2014 ACCVUER. All rights reserved.
//

#import "HistoryView.h"
#import "HistoryDataTableViewCell.h"
#import "UIViewController+MJPopupViewController.h"
#import "MainPagingScrollViewController.h"

@implementation HistoryView

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if(self)
    {

    }
    return self;
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

-(void)initViews
{
    self.collectedDataTableView.delegate = self;
    self.collectedDataTableView.dataSource = self;
    
    [self reloadHistoryTableView];
}

-(void)reloadHistoryTableView
{
    m_historyDataArr = [self getHistoryDataArrFromDB];
    [self.collectedDataTableView reloadData];
}

-(NSMutableArray *)getHistoryDataArrFromDB
{
    NSMutableArray *unSortiedArr = [SKDatabase getHistoryDataFromHistoryTable];
    
    if(unSortiedArr.count > 0)
    {
        NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"id" ascending:NO];
        return [[NSMutableArray alloc] initWithArray:[unSortiedArr sortedArrayUsingDescriptors:[NSArray arrayWithObjects:descriptor, nil]]];
    }
    
    return [[NSMutableArray alloc] init];
}

// historyDataDic
//accuracy = "65.000000";
//"avg_dl_throughput" = "35.381942";
//"avg_ul_throughput" = "45.138713";
//endtime = "20141106_140232";
//id = 1;
//latency = "4.803649";
//latitude = "37.493890";
//longitude = "126.818080";
//"max_dl_throughput" = "52.268692";
//"max_ul_throughput" = "45.989258";
//"network_type" = WIFI;
//"packet_loss_ratio" = "0.000000";
//starttime = "20141106_140128";

- (IBAction)clearButtonClicked:(id)sender
{
    [SKDatabase sEmptyTheDatabase];
    [self reloadHistoryTableView];
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [m_historyDataArr count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"HistoryDataTableViewCell";
    
    HistoryDataTableViewCell *historyDataCell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (historyDataCell == nil) {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"HistoryDataTableViewCell" owner:self options:nil];
        
        for (id oneObject in nib)
            if ([oneObject isKindOfClass:[HistoryDataTableViewCell class]])
                historyDataCell = (HistoryDataTableViewCell *)oneObject;
    }
    
    NSInteger row = [indexPath row];
    NSDictionary *cellData = [m_historyDataArr objectAtIndex:row];

    // date time
    NSString *dateTime = [cellData objectForKey:@"endtime"];
    NSDate *endTestDateTime = [SKGlobalMethods dateFromyyyyMMdd_HHmmssString:dateTime];
    
    NSString *date = [self yyMMddStringFormDate:endTestDateTime];
    NSString *time = [self HHmmStringFormDate:endTestDateTime];
    historyDataCell.dateLabel.text = date;
    historyDataCell.timeLabel.text = time;
    
    // network
    NSString *techName = [cellData objectForKey:@"network_type"];
    historyDataCell.networkLabel.text = NSLocalizedString(techName, nil);
    UIImage *techImg = [self getNetworkTechImgWithTechName:techName];
    if (techImg == nil)
    {
        historyDataCell.networkLabel.text = NSLocalizedString(techName, nil);
        [historyDataCell.networkLabel setHidden:NO];
        [historyDataCell.networkImage setHidden:YES];
    }
    else
    {
        [historyDataCell.networkImage setHidden:NO];
        [historyDataCell.networkLabel setHidden:YES];
        [historyDataCell.networkImage setImage:techImg];
    }
    
    // latency packet_loss
    NSString *latencyStr = [NSString stringWithFormat:@"%@", [cellData objectForKey:@"latency"]];
    if ([latencyStr isEqualToString:STR_FAIL] || [latencyStr isEqualToString:STR_UNKNOWN])
    {
        [historyDataCell.packetLossLabel setHidden:YES];
        [historyDataCell.latencyLabel setHidden:YES];
        [historyDataCell.latencyFailLabel setHidden:NO];
    }
    else
    {
        double latency = [[cellData objectForKey:@"latency"] doubleValue];
        historyDataCell.latencyLabel.text = [NSString stringWithFormat:@"%.1f",latency];
        double packetLossRatio = [[cellData objectForKey:@"packet_loss_ratio"] doubleValue];
        historyDataCell.packetLossLabel.text = [NSString stringWithFormat:@"(L:%.1f%%)",packetLossRatio];
        
        [historyDataCell.packetLossLabel setHidden:NO];
        [historyDataCell.latencyLabel setHidden:NO];
        [historyDataCell.latencyFailLabel setHidden:YES];
    }
    
    // download
    NSString *avgDLStr = [NSString stringWithFormat:@"%@", [cellData objectForKey:@"avg_dl_throughput"]];
    if ([avgDLStr isEqualToString:STR_FAIL] || [avgDLStr isEqualToString:STR_UNKNOWN])
    {
        [historyDataCell.downloadAvgLabel setHidden:YES];
        [historyDataCell.downloadPeakLabel setHidden:YES];
        [historyDataCell.downloadFailLabel setHidden:NO];
    }
    else
    {
        double avgDownload_1000Based = [[cellData objectForKey:@"avg_dl_throughput"] doubleValue];
        NSString *avgDownload = [SKGlobalMethods bitrateMbps1000BasedToString:avgDownload_1000Based];
        historyDataCell.downloadAvgLabel.text = [NSString stringWithFormat:@"%@", avgDownload];
        double maxDownload_1000Based = [[cellData objectForKey:@"max_dl_throughput"] doubleValue];
        NSString *maxDownload = [SKGlobalMethods bitrateMbps1000BasedToString:maxDownload_1000Based];
        historyDataCell.downloadPeakLabel.text = [NSString stringWithFormat:@"(P:%@)", maxDownload];
        
        [historyDataCell.downloadAvgLabel setHidden:NO];
        [historyDataCell.downloadPeakLabel setHidden:NO];
        [historyDataCell.downloadFailLabel setHidden:YES];
    }
    
    // upload
    NSString *avgULStr = [NSString stringWithFormat:@"%@", [cellData objectForKey:@"avg_ul_throughput"]];
    if ([avgULStr isEqualToString:STR_FAIL] || [avgULStr isEqualToString:STR_UNKNOWN])
    {
        [historyDataCell.uploadAvgLabel setHidden:YES];
        [historyDataCell.uploadPeakLabel setHidden:YES];
        [historyDataCell.uploadFailLabel setHidden:NO];
    }
    else
    {
        double avgUpload_1000Based = [[cellData objectForKey:@"avg_ul_throughput"] doubleValue];
        NSString *avgUpload = [SKGlobalMethods bitrateMbps1000BasedToString:avgUpload_1000Based];
        historyDataCell.uploadAvgLabel.text = [NSString stringWithFormat:@"%@", avgUpload];
        double maxUpload_1000Based = [[cellData objectForKey:@"max_ul_throughput"] doubleValue];
        NSString *maxUpload = [SKGlobalMethods bitrateMbps1000BasedToString:maxUpload_1000Based];
        historyDataCell.uploadPeakLabel.text = [NSString stringWithFormat:@"(P:%@)", maxUpload];
        
        [historyDataCell.uploadAvgLabel setHidden:NO];
        [historyDataCell.uploadPeakLabel setHidden:NO];
        [historyDataCell.uploadFailLabel setHidden:YES];
    }

    return historyDataCell;
}

#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
    HistoryDataDetailPopupViewController *vc = [storyboard instantiateViewControllerWithIdentifier:@"HistoryDataDetailPopupViewController"];
    
    NSDictionary *cellData = [m_historyDataArr objectAtIndex:[indexPath row]];
    
    vc.delegate = self;
    vc.m_historyCellDataDic = cellData;

    if([SKAAppDelegate getAppDelegate].mainPagingScrollVC != nil)
        [[SKAAppDelegate getAppDelegate].mainPagingScrollVC presentPopupViewController:vc animationType:MJPopupViewAnimationSlideBottomBottom isEnableBgTouch:NO];
}

#pragma mark - HistoryDataDetailPopupView
-(void)dismissHistoryDataDetailPopupView
{
    if([SKAAppDelegate getAppDelegate].mainPagingScrollVC != nil)
        [[SKAAppDelegate getAppDelegate].mainPagingScrollVC dismissPopupViewControllerWithanimationType:MJPopupViewAnimationSlideBottomBottom];
}

#pragma mark - etc

-(NSString *)HHmmStringFormDate:(NSDate *)date
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"HH:mm"];
    [dateFormatter setLocale:[NSLocale currentLocale]];
    [dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
    NSString *resultStr = [dateFormatter stringFromDate:date];
    return resultStr;
}

-(NSString *)yyMMddStringFormDate:(NSDate *)date
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yy/MM/dd"];
    [dateFormatter setLocale:[NSLocale currentLocale]];
    [dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
    NSString *resultStr = [dateFormatter stringFromDate:date];
    return resultStr;
}

-(UIImage *)getNetworkTechImgWithTechName:(NSString *)techName
{
    if ([techName isEqualToString:@"WIFI"])
    {
        return [UIImage imageNamed:@"History_Table_WIFI"];
    }
    else if ([techName isEqualToString:NSLocalizedString(@"CTRadioAccessTechnologyLTE", nil)])
    {
        return [UIImage imageNamed:@"History_Table_LTE"];
    }
    else if ([techName isEqualToString:NSLocalizedString(@"CTRadioAccessTechnologyWCDMA", nil)])
    {
        return [UIImage imageNamed:@"History_Table_WCDMA"];
    }
    else if ([techName isEqualToString:NSLocalizedString(@"CTRadioAccessTechnologyGPRS", nil)])
    {
        return [UIImage imageNamed:@"History_Table_GPRS"];
    }
    else if ([techName isEqualToString:NSLocalizedString(@"CTRadioAccessTechnologyEdge", nil)])
    {
        return [UIImage imageNamed:@"History_Table_Edge"];
    }
    else if ([techName isEqualToString:NSLocalizedString(@"CTRadioAccessTechnologyHSDPA", nil)])
    {
        return [UIImage imageNamed:@"History_Table_HSDPA"];
    }
    else if ([techName isEqualToString:NSLocalizedString(@"CTRadioAccessTechnologyHSUPA", nil)])
    {
        return [UIImage imageNamed:@"History_Table_HSUPA"];
    }
    else if ([techName isEqualToString:NSLocalizedString(@"CTRadioAccessTechnologyCDMA1x", nil)]
             || [techName isEqualToString:NSLocalizedString(@"CTRadioAccessTechnologyCDMAEVDORev0", nil)]
             || [techName isEqualToString:NSLocalizedString(@"CTRadioAccessTechnologyCDMAEVDORevA", nil)]
             || [techName isEqualToString:NSLocalizedString(@"CTRadioAccessTechnologyCDMAEVDORevB", nil)])
    {
        return [UIImage imageNamed: @"History_Table_CDMA"];
    }
    else if ([techName isEqualToString:NSLocalizedString(@"CTRadioAccessTechnologyeHRPD", nil)])
    {
        return [UIImage imageNamed:@"History_Table_eHRPD"];
    }
    else if ([techName isEqualToString:@"N/A"] || [techName isEqualToString:@""] || [techName isEqualToString:@"NA"])
    {
        return [UIImage imageNamed: @"History_Table_NA"];
    }
    else
    {
        return nil;
    }
}

@end
