//
//  ZBLogViewController.m
//  XXGPlayKit
//
//  Created by AI Assistant on 2025/1/20.
//

#import "ZBLogViewController.h"
#import "ZBLog.h"
#import "ZBConsoleDestinatioin.h"
#import "ZBFileDestination.h"
#import "XXGPlayKitConfig.h"

@interface ZBLogViewController ()
@property (nonatomic, strong) UITextView *textView;
@property (nonatomic, strong) ZBConsoleDestinatioin *consoleDestination;
@property (nonatomic, strong) ZBFileDestination *fileDestination;
@property (nonatomic, strong) NSDate *selectedDate; // 选中的日期，nil表示显示所有日志
@end

static ZBFileDestination *_sharedFileDestination = nil;
static ZBConsoleDestinatioin *_sharedConsoleDestination = nil;

@implementation ZBLogViewController

+ (void)setupLogger {
    // 清除现有目标
    [ZBLog zb_removeAllDestinations];

    // 添加控制台输出
    _sharedConsoleDestination = [[ZBConsoleDestinatioin alloc] init];
    _sharedConsoleDestination.zb_minLevel = ZBLogLevelVerbose;
#ifdef XXGPLAYKIT_DEBUG
    _sharedConsoleDestination.zb_minLevel = ZBLogLevelOff;
#endif
    [ZBLog zb_addDestination:_sharedConsoleDestination];

    // 添加文件输出
    _sharedFileDestination = [[ZBFileDestination alloc] init];
    _sharedFileDestination.zb_minLevel = ZBLogLevelOff;
    _sharedFileDestination.maxDays = 7;
    _sharedFileDestination.encryptionEnabled = YES;
    [ZBLog zb_addDestination:_sharedFileDestination];

    // 清理过期日志
    [_sharedFileDestination cleanupOldLogs];
}

+ (ZBFileDestination *)sharedFileDestination {
    return _sharedFileDestination;
}
+ (ZBConsoleDestinatioin *)sharedConsoleDestination {
    return _sharedConsoleDestination;
}

- (ZBConsoleDestinatioin *)consoleDestination {
    return _sharedConsoleDestination;
}

+ (void)showFromViewController:(UIViewController *)parentVC {
    ZBLogViewController *logVC = [[ZBLogViewController alloc] init];
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:logVC];
    nav.modalPresentationStyle = UIModalPresentationFullScreen;
    [parentVC presentViewController:nav animated:YES completion:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.title = __data_core.xxpk_tools_logger_ui_title;
    self.view.backgroundColor = [UIColor systemBackgroundColor];

    // 导航栏按钮
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]
                                            initWithBarButtonSystemItem:UIBarButtonSystemItemCancel
                                            target:self
                                            action:@selector(closeAction)];

    self.navigationItem.rightBarButtonItems = @[
        [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh
                                                      target:self
                                                      action:@selector(refreshAction)],
        [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction
                                                      target:self
                                                      action:@selector(shareAction)],
        [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemBookmarks
                                                      target:self
                                                      action:@selector(selectDateAction)]
    ];
    self.navigationController.navigationBar.layoutMargins = UIEdgeInsetsMake(0, 0, 0, -10);

    // 创建文本视图
    _textView = [[UITextView alloc] init];
    _textView.font = [UIFont systemFontOfSize:11];
    _textView.editable = NO;
    _textView.backgroundColor = [UIColor systemBackgroundColor];
    _textView.textColor = [UIColor labelColor];
    _textView.translatesAutoresizingMaskIntoConstraints = NO;
    _textView.showsVerticalScrollIndicator = YES;
    _textView.showsHorizontalScrollIndicator = YES;
    _textView.alwaysBounceVertical = YES;
    // 支持横向滚动
    _textView.scrollEnabled = YES;
    [self.view addSubview:_textView];

    // 约束
    [NSLayoutConstraint activateConstraints:@[
        [_textView.topAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.topAnchor],
        [_textView.leadingAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.leadingAnchor constant:8],
        [_textView.trailingAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.trailingAnchor constant:-8],
        [_textView.bottomAnchor constraintEqualToAnchor:self.view.bottomAnchor]
    ]];

    // 获取文件目标
    self.fileDestination = [ZBLogViewController sharedFileDestination];

    // 加载日志
    [self loadLogs];
}

- (void)loadLogs {
    if (!self.fileDestination) {
        _textView.text = __data_core.xxpk_tools_logger_ui_not_init;
        return;
    }

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSString *logs;
        if (self.selectedDate) {
            logs = [self.fileDestination readLogsForDate:self.selectedDate];
        } else {
            logs = [self.fileDestination readAllLogs];
        }

        dispatch_async(dispatch_get_main_queue(), ^{
            if (logs.length > 0) {
                self.textView.text = logs;
                // 滚动到底部
                [self.textView scrollRangeToVisible:NSMakeRange(logs.length - 1, 1)];
            } else {
                self.textView.text = __data_core.xxpk_tools_logger_ui_no_logs;
            }

            // 更新标题显示当前查看的日期
            [self updateTitle];
        });
    });
}

- (void)closeAction {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)refreshAction {
    [self loadLogs];
}

- (void)updateTitle {
    if (self.selectedDate) {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = __data_core.xxpk_tools_logger_ui_date_format;
        NSString *dateString = [formatter stringFromDate:self.selectedDate];

        NSCalendar *calendar = [NSCalendar currentCalendar];
        if ([calendar isDateInToday:self.selectedDate]) {
            self.title = __data_core.xxpk_tools_logger_ui_today;
        } else if ([calendar isDateInYesterday:self.selectedDate]) {
            self.title = __data_core.xxpk_tools_logger_ui_yesterday;
        } else {
            self.title = dateString;
        }
    } else {
        self.title = __data_core.xxpk_tools_logger_ui_all_logs;
    }
}

- (void)selectDateAction {
    if (!self.fileDestination) {
        return;
    }

    NSArray<NSDate *> *availableDates = [self.fileDestination allLogDates];
    if (availableDates.count == 0) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:__data_core.xxpk_tools_logger_ui_info
                                                                       message:__data_core.xxpk_tools_logger_ui_no_logs
                                                                preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:__data_core.xxpk_tools_logger_ui_ok style:UIAlertActionStyleDefault handler:nil]];
        [self presentViewController:alert animated:YES completion:nil];
        return;
    }

    UIAlertController *actionSheet = [UIAlertController alertControllerWithTitle:__data_core.xxpk_tools_logger_ui_select_date
                                                                         message:nil
                                                                  preferredStyle:UIAlertControllerStyleActionSheet];

    // 添加"所有日志"选项
    [actionSheet addAction:[UIAlertAction actionWithTitle:__data_core.xxpk_tools_logger_ui_all_logs
                                                    style:UIAlertActionStyleDefault
                                                  handler:^(UIAlertAction *action) {
        self.selectedDate = nil;
        [self loadLogs];
    }]];

    // 添加日期选项
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = __data_core.xxpk_tools_logger_ui_date_format;

    NSCalendar *calendar = [NSCalendar currentCalendar];

    for (NSDate *date in availableDates) {
        NSString *title;
        if ([calendar isDateInToday:date]) {
            title = __data_core.xxpk_tools_logger_ui_today;
        } else if ([calendar isDateInYesterday:date]) {
            title = __data_core.xxpk_tools_logger_ui_yesterday;
        } else {
            title = [formatter stringFromDate:date];
        }

        [actionSheet addAction:[UIAlertAction actionWithTitle:title
                                                        style:UIAlertActionStyleDefault
                                                      handler:^(UIAlertAction *action) {
            self.selectedDate = date;
            [self loadLogs];
        }]];
    }

    [actionSheet addAction:[UIAlertAction actionWithTitle:__data_core.xxpk_tools_logger_ui_cancel style:UIAlertActionStyleCancel handler:nil]];

    // iPad适配
    if ([UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPad) {
        actionSheet.popoverPresentationController.barButtonItem = self.navigationItem.rightBarButtonItems.lastObject;
    }

    [self presentViewController:actionSheet animated:YES completion:nil];
}

- (void)shareAction {
    if (!self.fileDestination) {
        return;
    }

    NSArray *logFiles = [self.fileDestination allLogFiles];
    if (logFiles.count == 0) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:__data_core.xxpk_tools_logger_ui_info
                                                                       message:__data_core.xxpk_tools_logger_ui_no_files
                                                                preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:__data_core.xxpk_tools_logger_ui_ok style:UIAlertActionStyleDefault handler:nil]];
        [self presentViewController:alert animated:YES completion:nil];
        return;
    }

    // 创建分享选项
    UIAlertController *actionSheet = [UIAlertController alertControllerWithTitle:__data_core.xxpk_tools_logger_ui_share_logs
                                                                         message:nil
                                                                  preferredStyle:UIAlertControllerStyleActionSheet];

    // 分享所有日志
    [actionSheet addAction:[UIAlertAction actionWithTitle:__data_core.xxpk_tools_logger_ui_share_all
                                                    style:UIAlertActionStyleDefault
                                                  handler:^(UIAlertAction *action) {
        [self shareAllLogs];
    }]];

    // 分享单个文件
    for (NSURL *fileURL in logFiles) {
        NSString *fileName = fileURL.lastPathComponent;
        [actionSheet addAction:[UIAlertAction actionWithTitle:[NSString stringWithFormat:__data_core.xxpk_tools_logger_ui_share_file, fileName]
                                                        style:UIAlertActionStyleDefault
                                                      handler:^(UIAlertAction *action) {
            [self shareLogFile:fileURL];
        }]];
    }

    [actionSheet addAction:[UIAlertAction actionWithTitle:__data_core.xxpk_tools_logger_ui_cancel style:UIAlertActionStyleCancel handler:nil]];

    // iPad适配
    if ([UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPad) {
        actionSheet.popoverPresentationController.barButtonItem = self.navigationItem.rightBarButtonItems.lastObject;
    }

    [self presentViewController:actionSheet animated:YES completion:nil];
}

- (void)shareAllLogs {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        // 使用原始内容进行分享，保持存储格式
        NSString *allLogs = [self.fileDestination readAllLogsRaw];

        dispatch_async(dispatch_get_main_queue(), ^{
            if (allLogs.length > 0) {
                UIActivityViewController *activityVC = [[UIActivityViewController alloc]
                                                       initWithActivityItems:@[allLogs]
                                                       applicationActivities:nil];

                // iPad适配
                if ([UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPad) {
                    activityVC.popoverPresentationController.barButtonItem = self.navigationItem.rightBarButtonItems.lastObject;
                }

                [self presentViewController:activityVC animated:YES completion:nil];
            }
        });
    });
}

- (void)shareLogFile:(NSURL *)fileURL {
    UIActivityViewController *activityVC = [[UIActivityViewController alloc]
                                           initWithActivityItems:@[fileURL]
                                           applicationActivities:nil];

    // iPad适配
    if ([UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPad) {
        activityVC.popoverPresentationController.barButtonItem = self.navigationItem.rightBarButtonItems.lastObject;
    }

    [self presentViewController:activityVC animated:YES completion:nil];
}

@end
