//
//  ZYJQNUpToken.m
//  ZYJQiniuSDK
//
//  Created by bailong on 15/6/7.
//  Copyright (c) 2015年 Qiniu. All rights reserved.
//

#import "ZYJQNUrlSafeBase64.h"
#import "ZYJQNUpToken.h"

@interface ZYJQNUpToken ()

- (instancetype)init:(NSDictionary *)policy token:(NSString *)token;

@end

@implementation ZYJQNUpToken

- (instancetype)init:(NSDictionary *)policy token:(NSString *)token {
    if (self = [super init]) {
        _token = token;
        _access = [self getAccess];
        _bucket = [self getBucket:policy];
        _hasReturnUrl = (policy[@"returnUrl"] != nil);
    }

    return self;
}

- (NSString *)getAccess {

    NSRange range = [_token rangeOfString:@":" options:NSCaseInsensitiveSearch];
    return [_token substringToIndex:range.location];
}

- (NSString *)getBucket:(NSDictionary *)info {

    NSString *scope = [info objectForKey:@"scope"];
    if (!scope || [scope isKindOfClass:[NSNull class]]) {
        return @"";
    }

    NSRange range = [scope rangeOfString:@":"];
    if (range.location == NSNotFound) {
        return scope;
    }
    return [scope substringToIndex:range.location];
}

+ (instancetype)parse:(NSString *)token {
    if (token == nil) {
        return nil;
    }
    NSArray *array = [token componentsSeparatedByString:@":"];
    if (array == nil || array.count != 3) {
        return nil;
    }

    NSData *data = [ZYJQNUrlSafeBase64 decodeString:array[2]];
    if (!data) {
        return nil;
    }
    
    NSError *tmp = nil;
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&tmp];
    if (tmp != nil || dict[@"scope"] == nil || dict[@"deadline"] == nil) {
        return nil;
    }
    return [[ZYJQNUpToken alloc] init:dict token:token];
}

- (NSString *)index {
    return [NSString stringWithFormat:@"%@:%@", _access, _bucket];
}

@end
