FirmwareDownloadController.m 9.88キロバイト
//
//  FirmwareDownloadController.m
//  jacket_ios
//
//  Created by ドラッサル 亜嵐 on 2017/06/06.
//  Copyright © 2017年 ドラッサル 亜嵐. All rights reserved.
//

#import "FirmwareDownloadController.h"
#import "FirmwareDownloadControllerTableViewCell.h"
#import "Operation.h"
#import "DBManager.h"

@interface FirmwareDownloadController ()

@end

@implementation FirmwareDownloadController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void)viewWillAppear:(BOOL)animated {
    self.lastProtocolDelegate = self.protocol.delegate;
    self.protocol.delegate = self;

    bleCommandState = FIRMWARE_DOWNLOAD__EEPROM_READ_ID;
    [self bleCommandTask];
}

- (void)viewWillDisappear:(BOOL)animated {
    self.protocol.delegate = self.lastProtocolDelegate;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void) getDownloadList {
    selectionEnabled = 1;
    
    arrResult = [[NSMutableArray alloc] init];
    
    UINib *nib = [UINib nibWithNibName:@"FirmwareDownloadControllerTableViewCell" bundle:nil];
    [tblFirmware registerNib:nib forCellReuseIdentifier:@"mycell"];
    tblFirmware.delegate = self;
    tblFirmware.dataSource = self;
    
    [[Operation sharedOperation] getFirmwareList:strId
                                      deviceType:strType
                                     deviceModel:strModel
                                        deviceOs:strOs
                                      appVersion:@"appVersion"
                                         success:^(id JSON) {
                                             NSLog(@"SUCCESS!");
                                             
                                             if([JSON valueForKey:@"firmware_list"]) {
                                                 [arrResult removeAllObjects];
                                                 
                                                 NSDictionary *firmwareList = [JSON valueForKey:@"firmware_list"];
                                                 
                                                 for(id selectedKey in firmwareList) {
                                                     NSDictionary *firmwareListRecord = [firmwareList valueForKey:selectedKey];
                                                     NSMutableDictionary *detailDict = [[NSMutableDictionary alloc] init];
                                                     [detailDict setValue:selectedKey forKey:@"uuid"];
                                                     for(id selectedSubKey in firmwareListRecord) {
                                                         [detailDict setValue:[firmwareListRecord valueForKey:selectedSubKey] forKey:selectedSubKey];
                                                     }
                                                     [arrResult addObject:detailDict];
                                                 }
                                             }
                                             [tblFirmware reloadData];
                                         } failure:^(NSError *error, id JSON) {
                                             NSLog(@"FAIL!");
                                         }];
}

- (IBAction)cancelButtonClicked:(id)sender {
    [self dismissViewControllerAnimated:YES completion:Nil];
}

- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if(selectionEnabled == 1) {
        return indexPath;
    } else {
        return nil;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger row = [indexPath row];
    NSDictionary *dataRecord = [arrResult objectAtIndex:row];

    NSString *filename = [dataRecord valueForKey:@"uuid"];
    
    selectionEnabled = 0;
    
    [[Operation sharedOperation] streamToFile:[NSString stringWithFormat:@"%@%@",URL_BASE,[NSString stringWithFormat:URL_PATH_STORE_FIRMWARE, filename]]
                                   saveToPath:[NSString stringWithFormat:@"save/%@",filename]
                                progressBlock:^(double fractionCompleted) {
                                    //NSLog(@"Progress: %f", fractionCompleted);
                                    lblPercentComplete.text = [NSString stringWithFormat:@"%f%%", fractionCompleted * 100];
                                }
                                      success:^(NSString *savedTo) {
                                          NSLog(@"Saved to %@",savedTo);
                                          [[DBManager sharedInstance] saveFirmwareData:[dataRecord valueForKey:@"uuid"]
                                                                            deviceType:[dataRecord valueForKey:@"devicetype"]
                                                                           deviceModel:[dataRecord valueForKey:@"devicemodel"]
                                                                               version:[dataRecord valueForKey:@"version"]
                                                                          versionStamp:[dataRecord valueForKey:@"version_Stamp"]
                                                                                  file:[dataRecord valueForKey:@"file"]];
                                          //[self saveVideoInfo:video.identifier videoItag:[NSString stringWithFormat:@"%@",videoQuality] videoFilename:[NSString stringWithFormat:@"%@_%@.mp4",video.identifier,videoQuality]];
                                          //[self showAlert:@"アプリに保存" message:@"保存完了"];
                                          selectionEnabled = 1;
                                          lblPercentComplete.text = @"完了";
                                      }
                                      failure:^(NSError *error) {
                                          //[self showAlert:@"アプリに保存" message:@"保存完了"];
                                          selectionEnabled = 1;
                                          lblPercentComplete.text = @"失敗";
                                      }];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return [arrResult count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"mycell";
    FirmwareDownloadControllerTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
    
    NSInteger row = [indexPath row];
    NSDictionary *dataRecord = [arrResult objectAtIndex:row];
    
    // Configure the cell...
    UIFont *newFont = [UIFont fontWithName:@"Arial" size:11.0];
    cell.lblTitle.font = newFont;
    cell.lblTitle.text = [dataRecord valueForKey:@"file"];
    
    newFont = [UIFont fontWithName:@"Arial" size:11.0];
    cell.lblSubtitle.font = newFont;
    cell.lblSubtitle.text = [dataRecord valueForKey:@"uuid"];
    
    return cell;
}

- (BOOL)bleCommandTask {
    switch(bleCommandState) {
        case FIRMWARE_DOWNLOAD__EEPROM_READ_ID:
            [[self protocol]putData:@"infoDeviceId" data:nil];
            break;
        case FIRMWARE_DOWNLOAD__EEPROM_READ_MODEL:
            [[self protocol]putData:@"infoDeviceModel" data:nil];
            break;
        case FIRMWARE_DOWNLOAD__EEPROM_READ_TYPE:
            [[self protocol]putData:@"infoDeviceType" data:nil];
            break;
        case FIRMWARE_DOWNLOAD__EEPROM_READ_OS:
            [[self protocol]putData:@"infoDeviceOs" data:nil];
            break;
        case FIRMWARE_DOWNLOAD__EEPROM_READ_ID_DONE:
            bleCommandState = FIRMWARE_DOWNLOAD__EEPROM_READ_MODEL;
            [self bleCommandTask];
            break;
        case FIRMWARE_DOWNLOAD__EEPROM_READ_MODEL_DONE:
            bleCommandState = FIRMWARE_DOWNLOAD__EEPROM_READ_TYPE;
            [self bleCommandTask];
            break;
        case FIRMWARE_DOWNLOAD__EEPROM_READ_TYPE_DONE:
            bleCommandState = FIRMWARE_DOWNLOAD__EEPROM_READ_OS;
            [self bleCommandTask];
            break;
        case FIRMWARE_DOWNLOAD__EEPROM_READ_OS_DONE:
            bleCommandState = FIRMWARE_DOWNLOAD__DONE;
            [self bleCommandTask];
            break;
        case FIRMWARE_DOWNLOAD__DONE:
        {
            NSLog(@"Ble command set done!");
            [self getDownloadList];
            break;
        }
    }
    return false;
}

- (void)protocolDidGetData:(NSString *)dataType data:(NSString *)dataData {
    if([dataType isEqualToString:@"infoDeviceId"]) {
        NSLog(@"infoDeviceId");
        strId = dataData;
        bleCommandState = FIRMWARE_DOWNLOAD__EEPROM_READ_ID_DONE;
        [self bleCommandTask];
    } else if([dataType isEqualToString:@"infoDeviceModel"]) {
        NSLog(@"infoDeviceModel");
        strModel = dataData;
        bleCommandState = FIRMWARE_DOWNLOAD__EEPROM_READ_MODEL_DONE;
        [self bleCommandTask];
    } else if([dataType isEqualToString:@"infoDeviceType"]) {
        NSLog(@"infoDeviceType");
        strType = dataData;
        bleCommandState = FIRMWARE_DOWNLOAD__EEPROM_READ_TYPE_DONE;
        [self bleCommandTask];
    } else if([dataType isEqualToString:@"infoDeviceOs"]) {
        NSLog(@"infoDeviceOs");
        strOs = dataData;
        bleCommandState = FIRMWARE_DOWNLOAD__EEPROM_READ_OS_DONE;
        [self bleCommandTask];
    }
}

/*
#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.
}
*/

@end