//
//  IMLEXObjectExplorer.m
//  IMLEX
//
//  Created by Tanner Bennett on 8/28/19.
//  Copyright © 2019 Flipboard. All rights reserved.
//

#import "IMLEXObjectExplorer.h"
#import "IMLEXUtility.h"
#import "IMLEXRuntimeUtility.h"
#import "NSObject+Reflection.h"
#import "IMLEXRuntime+Compare.h"
#import "IMLEXRuntime+UIKitHelpers.h"
#import "IMLEXPropertyAttributes.h"
#import "NSObject+Reflection.h"
#import "IMLEXMetadataSection.h"
#import "NSUserDefaults+IMLEX.h"

@interface IMLEXObjectExplorer () {
    NSMutableArray<NSArray<IMLEXProperty *> *> *_allProperties;
    NSMutableArray<NSArray<IMLEXProperty *> *> *_allClassProperties;
    NSMutableArray<NSArray<IMLEXIvar *> *> *_allIvars;
    NSMutableArray<NSArray<IMLEXMethod *> *> *_allMethods;
    NSMutableArray<NSArray<IMLEXMethod *> *> *_allClassMethods;
    NSMutableArray<NSArray<IMLEXProtocol *> *> *_allConformedProtocols;
    NSMutableArray<IMLEXStaticMetadata *> *_allInstanceSizes;
    NSMutableArray<IMLEXStaticMetadata *> *_allImageNames;
    NSString *_objectDescription;
}
@end

@implementation IMLEXObjectExplorer

#pragma mark - Initialization

+ (id)forObject:(id)objectOrClass {
    return [[self alloc] initWithObject:objectOrClass];
}

- (id)initWithObject:(id)objectOrClass {
    NSParameterAssert(objectOrClass);
    
    self = [super init];
    if (self) {
        _object = objectOrClass;
        _objectIsInstance = !object_isClass(objectOrClass);
        
        [self reloadMetadata];
    }

    return self;
}


#pragma mark - Public

- (NSString *)objectDescription {
    if (!_objectDescription) {
        // Hard-code UIColor description
        if ([self.object isKindOfClass:[UIColor class]]) {
            CGFloat h, s, l, r, g, b, a;
            [self.object getRed:&r green:&g blue:&b alpha:&a];
            [self.object getHue:&h saturation:&s brightness:&l alpha:nil];

            return [NSString stringWithFormat:
                @"HSL: (%.3f, %.3f, %.3f)\nRGB: (%.3f, %.3f, %.3f)\nAlpha: %.3f",
                h, s, l, r, g, b, a
            ];
        }

        NSString *description = [IMLEXRuntimeUtility safeDescriptionForObject:self.object];

        if (!description.length) {
            NSString *address = [IMLEXUtility addressOfObject:self.object];
            return [NSString stringWithFormat:@"Object at %@ returned empty description", address];
        }
        
        if (description.length > 10000) {
            description = [description substringToIndex:10000];
        }

        _objectDescription = description;
    }

    return _objectDescription;
}

- (void)setClassScope:(NSInteger)classScope {
    _classScope = classScope;
    
    [self reloadScopedMetadata];
}

- (void)reloadMetadata {
    _allProperties = [NSMutableArray new];
    _allClassProperties = [NSMutableArray new];
    _allIvars = [NSMutableArray new];
    _allMethods = [NSMutableArray new];
    _allClassMethods = [NSMutableArray new];
    _allConformedProtocols = [NSMutableArray new];
    _allInstanceSizes = [NSMutableArray new];
    _allImageNames = [NSMutableArray new];
    _objectDescription = nil;

    [self reloadClassHierarchy];
    
    NSUserDefaults *defaults = NSUserDefaults.standardUserDefaults;
    BOOL hideBackingIvars = defaults.IMLEX_explorerHidesPropertyIvars;
    BOOL hidePropertyMethods = defaults.IMLEX_explorerHidesPropertyMethods;
    BOOL showMethodOverrides = defaults.IMLEX_explorerShowsMethodOverrides;

    // Loop over each class and each superclass, collect
    // the fresh and unique metadata in each category
    Class superclass = nil;
    NSInteger count = self.classHierarchyClasses.count;
    NSInteger rootIdx = count - 1;
    for (NSInteger i = 0; i < count; i++) {
        Class cls = self.classHierarchyClasses[i];
        superclass = (i < rootIdx) ? self.classHierarchyClasses[i+1] : nil;

        [_allProperties addObject:[self
            metadataUniquedByName:[cls IMLEX_allInstanceProperties]
            superclass:superclass
            kind:IMLEXMetadataKindProperties
            skip:showMethodOverrides
        ]];
        [_allClassProperties addObject:[self
            metadataUniquedByName:[cls IMLEX_allClassProperties]
            superclass:superclass
            kind:IMLEXMetadataKindClassProperties
            skip:showMethodOverrides
        ]];
        [_allIvars addObject:[self
            metadataUniquedByName:[cls IMLEX_allIvars]
            superclass:nil
            kind:IMLEXMetadataKindIvars
            skip:NO
        ]];
        [_allMethods addObject:[self
            metadataUniquedByName:[cls IMLEX_allInstanceMethods]
            superclass:superclass
            kind:IMLEXMetadataKindMethods
            skip:showMethodOverrides
        ]];
        [_allClassMethods addObject:[self
            metadataUniquedByName:[cls IMLEX_allClassMethods]
            superclass:superclass
            kind:IMLEXMetadataKindClassMethods
            skip:showMethodOverrides
        ]];
        [_allConformedProtocols addObject:[self
            metadataUniquedByName:[cls IMLEX_protocols]
            superclass:superclass
            kind:IMLEXMetadataKindProtocols
            skip:NO
        ]];
        
        // TODO: join instance size, image name, and class hierarchy into a single model object
        // This would greatly reduce the laziness that has begun to manifest itself here
        [_allInstanceSizes addObject:[IMLEXStaticMetadata
            style:IMLEXStaticMetadataRowStyleKeyValue
            title:@"Instance Size" number:@(class_getInstanceSize(cls))
        ]];
        [_allImageNames addObject:[IMLEXStaticMetadata
            style:IMLEXStaticMetadataRowStyleDefault
            title:@"Image Name" string:@(class_getImageName(cls) ?: "Created at Runtime")
        ]];
    }
    
    _classHierarchy = [IMLEXStaticMetadata classHierarchy:self.classHierarchyClasses];
    
    NSArray<NSArray<IMLEXProperty *> *> *properties = _allProperties;
    
    // Potentially filter property-backing ivars
    if (hideBackingIvars) {
        NSArray<NSArray<IMLEXIvar *> *> *ivars = _allIvars.copy;
        _allIvars = [ivars IMLEX_mapped:^id(NSArray<IMLEXIvar *> *list, NSUInteger idx) {
            // Get a set of all backing ivar names for the current class in the hierarchy
            NSSet *ivarNames = [NSSet setWithArray:({
                [properties[idx] IMLEX_mapped:^id(IMLEXProperty *p, NSUInteger idx) {
                    // Nil if no ivar, and array is flatted
                    return p.attributes.backingIvar;
                }];
            })];
            
            // Remove ivars whose name is in the ivar names list
            return [list IMLEX_filtered:^BOOL(IMLEXIvar *ivar, NSUInteger idx) {
                return ![ivarNames containsObject:ivar.name];
            }];
        }];
    }
    
    // Potentially filter property-backing methods
    if (hidePropertyMethods) {
        NSArray<NSArray<IMLEXMethod *> *> *methods = _allMethods.copy;
        _allMethods = [methods IMLEX_mapped:^id(NSArray<IMLEXMethod *> *list, NSUInteger idx) {
            // Get a set of all property method names for the current class in the hierarchy
            NSSet *methodNames = [NSSet setWithArray:({
                [properties[idx] IMLEX_flatmapped:^NSArray *(IMLEXProperty *p, NSUInteger idx) {
                    if (p.likelyGetterExists) {
                        if (p.likelySetterExists) {
                            return @[p.likelyGetterString, p.likelySetterString];
                        }
                        
                        return @[p.likelyGetterString];
                    } else if (p.likelySetterExists) {
                        return @[p.likelySetterString];
                    }
                    
                    return nil;
                }];
            })];
            
            // Remove ivars whose name is in the ivar names list
            return [list IMLEX_filtered:^BOOL(IMLEXMethod *method, NSUInteger idx) {
                return ![methodNames containsObject:method.selectorString];
            }];
        }];
    }

    // Set up UIKit helper data
    // Really, we only need to call this on properties and ivars
    // because no other metadata types support editing.
    for (NSArray *matrix in @[_allProperties, _allIvars, /* _allMethods, _allClassMethods, _allConformedProtocols */]) {
        for (NSArray *metadataByClass in matrix) {
            for (id<IMLEXRuntimeMetadata> metadata in metadataByClass) {
                metadata.tag = metadata.isEditable ? @YES : nil;
            }
        }
    }
    
    [self reloadScopedMetadata];
}


#pragma mark - Private

- (void)reloadScopedMetadata {
    _properties = self.allProperties[self.classScope];
    _classProperties = self.allClassProperties[self.classScope];
    _ivars = self.allIvars[self.classScope];
    _methods = self.allMethods[self.classScope];
    _classMethods = self.allClassMethods[self.classScope];
    _conformedProtocols = self.allConformedProtocols[self.classScope];
    _instanceSize = self.allInstanceSizes[self.classScope];
    _imageName = self.allImageNames[self.classScope];
}

/// Accepts an array of IMLEX metadata objects and discards objects
/// with duplicate names, as well as properties and methods which
/// aren't "new" (i.e. those which the superclass responds to)
- (NSArray *)metadataUniquedByName:(NSArray *)list
                        superclass:(Class)superclass
                              kind:(IMLEXMetadataKind)kind
                              skip:(BOOL)skip {
    if (skip) {
        return list;
    }
    
    // Remove items with same name and return filtered list
    NSMutableSet *names = [NSMutableSet new];
    return [list IMLEX_filtered:^BOOL(id obj, NSUInteger idx) {
        NSString *name = [obj name];
        if ([names containsObject:name]) {
            return NO;
        } else {
            [names addObject:name];

            // Skip methods and properties which are just overrides,
            // potentially skip ivars and methods associated with properties
            switch (kind) {
                case IMLEXMetadataKindProperties:
                    if ([superclass instancesRespondToSelector:[obj likelyGetter]]) {
                        return NO;
                    }
                    break;
                case IMLEXMetadataKindClassProperties:
                    if ([superclass respondsToSelector:[obj likelyGetter]]) {
                        return NO;
                    }
                    break;
                case IMLEXMetadataKindMethods:
                    if ([superclass instancesRespondToSelector:NSSelectorFromString(name)]) {
                        return NO;
                    }
                    break;
                case IMLEXMetadataKindClassMethods:
                    if ([superclass respondsToSelector:NSSelectorFromString(name)]) {
                        return NO;
                    }
                    break;

                case IMLEXMetadataKindProtocols:
                case IMLEXMetadataKindClassHierarchy:
                case IMLEXMetadataKindOther:
                    return YES; // These types are already uniqued
                    break;
                    
                // Ivars cannot be overidden
                case IMLEXMetadataKindIvars: break;
            }

            return YES;
        }
    }];
}


#pragma mark - Superclasses

- (void)reloadClassHierarchy {
    // The class hierarchy will never contain metaclass objects by this logic;
    // it is always the same for a given class and instances of it
    _classHierarchyClasses = [[self.object class] IMLEX_classHierarchy];
}

@end
