//
//  LineSDKJSONWebToken+RawString.m
//  XenonSDK
//
//  Created by fq on 2021/1/21.
//  Copyright © 2021 SAGESSE. All rights reserved.
//

#import "LineSDKJSONWebToken+RawString.h"
#import <objc/runtime.h>

@implementation LineSDKJSONWebToken (RawString)

+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        [self ty_swizzleInstanceMethod:@selector(initWithString:) with:@selector(ty_initWithString:)];
    });
}

- (instancetype)ty_initWithString:(NSString *)string {
    id instance = [self ty_initWithString:string];
    [instance ty_setAssociate:string withKey:@"rawString"];
    return instance;
}

- (NSString *)rawString {
    return [self ty_getAssociateWithKey:@"rawString"];
}


+ (BOOL)ty_swizzleInstanceMethod:(SEL)oriSel with:(SEL)swiSel {
    Method oriMethod = class_getInstanceMethod(self, oriSel);
    Method swiMethod = class_getInstanceMethod(self, swiSel);
    if (!oriMethod || !swiMethod) return NO;
    
    class_addMethod(self,
                    oriSel,
                    class_getMethodImplementation(self, oriSel),
                    method_getTypeEncoding(oriMethod));
    class_addMethod(self,
                    swiSel,
                    class_getMethodImplementation(self, swiSel),
                    method_getTypeEncoding(swiMethod));
    
    method_exchangeImplementations(class_getInstanceMethod(self, oriSel),
                                   class_getInstanceMethod(self, swiSel));
    return YES;
}

//相当于 setValue:forKey 进行关联value对象
- (void)ty_setAssociate:(id)obj withKey:(const void * _Nonnull)key {
    if (!key) {
        return;
    }
    objc_setAssociatedObject(self, key, obj, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

//用来读取对象
- (id)ty_getAssociateWithKey:(const void * _Nonnull)key {
    if (!key) {
        return nil;
    }
    return objc_getAssociatedObject(self, key);
}
@end