//
//  EquipPackagesManager.m
//  REGA AW109SP
//
//  Created by Vadim on 12/2/14.
//
//

#import "EquipPackagesManager.h"
#import "EquipmentPackages.h"

#define ALL_PACKAGES_KEY @"AllEquipmentPackages"
#define DEFAULT_CONFIGS_MAP_KEY @"DefaultConfigsMap"
#define DEFAULT_CONFIG_NUMBER_KEY @"AllDefaultConfigs"
#define NUMBER_OF_CONFIGS @"NumberOfConfigs"

@interface EquipPackagesManager()

@property int maxConfigs;

@end

@implementation EquipPackagesManager {
    NSMutableDictionary* equipPacksDict_;
    NSMutableDictionary* defaultConfigsMap_;
    NSMutableArray* defaultEquipPacks_;
}

#pragma mark- Initialization

+ (EquipPackagesManager*)sharedInstance {
    static dispatch_once_t pred;
    static EquipPackagesManager *sharedIinstance = nil;
    
    dispatch_once(&pred, ^{
        sharedIinstance = [[[self class] alloc] init];
    });
    return sharedIinstance;
}

+ (void)initializeWithMaxConfigs:(int)numberOfConfigs {
    [[NSUserDefaults standardUserDefaults] setInteger:numberOfConfigs forKey:NUMBER_OF_CONFIGS];
    [EquipPackagesManager sharedInstance];
}

- (id)init {
    self = [super init];
    if (self) {
        NSArray* packagesKeys = [[NSUserDefaults standardUserDefaults] arrayForKey:ALL_PACKAGES_KEY];
        equipPacksDict_ = [NSMutableDictionary new];
        for (NSString* key in packagesKeys) {
            EquipmentPackages* pack = [[EquipmentPackages alloc] initWithSerializeKey:key];
            [equipPacksDict_ setValue:pack forKey:key];
        }
        
        defaultConfigsMap_ = [[[NSUserDefaults standardUserDefaults] dictionaryForKey:DEFAULT_CONFIGS_MAP_KEY] mutableCopy];
        if (!defaultConfigsMap_) {
            defaultConfigsMap_ = [NSMutableDictionary new];
        }
        
        defaultEquipPacks_ = [NSMutableArray new];
        _maxConfigs = [[NSUserDefaults standardUserDefaults] integerForKey:NUMBER_OF_CONFIGS];
        for (int i = 0; i < _maxConfigs; ++i) {
            NSString* serializeKey = [NSString stringWithFormat:@"Default_%d", i];
            EquipmentPackages* pack = [[EquipmentPackages alloc] initWithSerializeKey:serializeKey];
            pack.configNumber = i;
            [defaultEquipPacks_ addObject:pack];
        }
    }
    return self;
}

#pragma mark- API Methods

- (void)downloadDefaultConfigsFromURL:(NSString *)downloadURL completionBlock:(void (^)(NSString *))block {
    __block NSString* errorString;
    __block int count = _maxConfigs;
    
    NSString *dedicatedCustomerData  = [[NSUserDefaults standardUserDefaults]  stringForKey: @"dedicatedCustomerData"];
    if (dedicatedCustomerData.length < 2) {
        dedicatedCustomerData = @"";
    }     
    if ([dedicatedCustomerData rangeOfString:@"PHIspecials"].location != NSNotFound  ) {         
        //NSLog(@"import for PHI _maxConfigs %.0d", _maxConfigs);        
        for (int i = 1; i <= _maxConfigs && !errorString; i++) {
            EquipmentPackages* pack = defaultEquipPacks_[i-1];
            pack.downloadURL=[downloadURL stringByAppendingFormat:@"&filenumber=%i",i];
            
            //pack.downloadURL=[downloadURL stringByAppendingFormat:@"/%i", i];          
            
            //pack.downloadURL=@"https://api.phiairmedical.com/0.1/EquipmentList/AS350B3/AIR EVAC 1/1";
            
            //NSLog(@"pack.downloadURL %@", pack.downloadURL);    
            
            //pack.pack.downloadURL=[downloadURL stringByAppendingFormat:@”/%i”,i];
            //NSLog(@"URL: %@", pack.downloadURL);
            [pack downloadPackagesFileWithCompletionBlock:^(bool status, NSString *error) {
                if (!status) {
                    errorString = error;
                    block(errorString);
                } else {
                    count--;
                    if (count == 0) {
                        block(nil);
                    }
                    
                }
            }];
        } 
        
    }else{
        
        //this downloads only one list - new system for example BABCOCK
        //downloadURL = @"http://gyronimo.kulanaserver.com/manager/webservice_get_equipment.php?customer=b6689432&callsign=G-HEMC";    
        //NSLog(@"downloadDefaultConfigsFromURL: downloadURL %@", downloadURL);
        for (int i = 1; i <= 1 && !errorString; i++) {
            EquipmentPackages* pack = defaultEquipPacks_[i-1];
            pack.downloadURL=[downloadURL stringByAppendingFormat:@"&filenumber=%i",i];
            //NSLog(@"EquipPackagesManager: downloadDefaultConfigsFromURL: %@", pack.downloadURL);
            [pack downloadPackagesFileWithCompletionBlock:^(bool status, NSString *error) {
                if (!status) {
                    errorString = error;
                    block(errorString);
                } else {
                    count--;
                    if (count == 0) {
                        block(nil);
                    }
                }
            }];
            NSString *callsignForImport = [[NSUserDefaults standardUserDefaults]  stringForKey:@"callsignForImport"];        
            //NSLog(@"callsignForImport:  %@", callsignForImport);        
            [[EquipPackagesManager sharedInstance] addNewPackageWithKey:callsignForImport andDefaultConfig:0]; 
        }// end for next
        
        
        
    }
    
    
  
    
    
    
}

- (void)exportPackagesToURL:(NSString *)uploadURL completionBlock:(void (^)(NSString *))block {
    __block NSString* errorString;
    __block int count = equipPacksDict_.count;
    
    for (EquipmentPackages* pack in [equipPacksDict_ allValues]) {
        if (errorString) {
            return;
        }
        
        pack.uploadURL=[uploadURL stringByAppendingFormat:@"&filenumber=%i",pack.configNumber];
        [pack uploadPackagesFileWithCompletionBlock:^(bool status, NSString *error) {
            if (!status) {
                errorString = error;
                block(errorString);
            } else {
                count--;
                if (count == 0) {
                    block(nil);
                }
                
            }
        }];
    }
}

- (void)exportPackageForKey:(NSString *)key toURL:(NSString *)uploadURL completionBlock:(void (^)(NSString *))block {
    EquipmentPackages* pack = [self packageForKey:key];
    if (key) {
        
        
        //pack.uploadURL=[uploadURL stringByAppendingFormat:@"&filenumber=%i",pack.configNumber];
        
        pack.uploadURL=[uploadURL stringByAppendingFormat:@"&filenumber=%i",pack.configNumber+1];
        
        [pack uploadPackagesFileWithCompletionBlock:^(bool status, NSString *error) {
            if (!status) {
                block(error);
            } else {
                block(nil);
            }
        }];
    } else {
        block([NSString stringWithFormat:@"Package for flight %@ doesn't exist", key]);
    }
}

- (EquipmentPackages*)addNewPackageWithKey:(NSString*)key andDefaultConfig:(int)configIndex {
    if (configIndex < 0 || configIndex >= defaultEquipPacks_.count) return nil;
    
    EquipmentPackages* config = defaultEquipPacks_[configIndex];
    EquipmentPackages* pack = [[EquipmentPackages alloc] initWithPackages:config andSerializeKey:key];
    pack.configNumber = configIndex;
    [equipPacksDict_ setValue:pack forKey:key];
    
    [[NSUserDefaults standardUserDefaults] setObject:[equipPacksDict_  allKeys] forKey:ALL_PACKAGES_KEY];
    return pack;
}

- (EquipmentPackages*)addNewPackageWithKey:(NSString *)key copyingFromPackage:(EquipmentPackages *)package {
    EquipmentPackages* pack = [[EquipmentPackages alloc] initWithPackages:package andSerializeKey:key];
    [equipPacksDict_ setValue:pack forKey:key];
    [[NSUserDefaults standardUserDefaults] setObject:[equipPacksDict_  allKeys] forKey:ALL_PACKAGES_KEY];
    return pack;
}

- (void)resetPackageForKey:(NSString *)key fromConfig:(int)configIndex {
    if (configIndex < 0 || configIndex >= defaultEquipPacks_.count) return;
    
    EquipmentPackages* config = defaultEquipPacks_[configIndex];
    EquipmentPackages* pack = [self packageForKey:key];
    pack.configNumber = configIndex;
    [pack copyFromPackage:config];
}

- (EquipmentPackages*)packageForKey:(NSString *)key {
    return [equipPacksDict_ valueForKey:key];
}

- (void)reset {
    for (EquipmentPackages* pack in [equipPacksDict_ allValues]) {
        [pack wipeOut];
    }
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:ALL_PACKAGES_KEY];
    equipPacksDict_ = [NSMutableDictionary new];
}

#pragma mark- Private Methods

@end
