//
//  FloatingWindow.m
//  nochange
//
//  Created by mac on 2024/7/29.
//

#import "FloatingWindow.h"
#import "IPhoneHertbeat.h"
#import "MyAdTask2.h"
#import "MyEventBus.h"
#import "UIView+Toast.h"
#import "XSHelper.h"
#import "XSPhoneConfig.h"
#import "XSPhoneInfo.h"
#import <Foundation/Foundation.h>

@interface FloatingWindow () {
}

@end

@implementation FloatingWindow

- (instancetype)initWithFrame {
  CGRect screenBounds = [UIScreen mainScreen].bounds;
  CGFloat floatingWindowWidth = 180;
  CGFloat floatingWindowHeight = 160;
  CGFloat xPosition = 0;
  CGFloat yPosition = screenBounds.size.height - floatingWindowHeight;

  CGRect frame = CGRectMake(xPosition, yPosition, floatingWindowWidth,
                            floatingWindowHeight);
  self = [super initWithFrame:frame];
  if (self) {
    UIPanGestureRecognizer *panRecognizer =
        [[UIPanGestureRecognizer alloc] initWithTarget:self
                                                action:@selector(detectPan:)];
    [self addGestureRecognizer:panRecognizer];

    self.backgroundColor = RGB(193, 41, 48); // RGB(85, 172, 119);
    self.layer.cornerRadius = 10;
    self.clipsToBounds = YES;

    [self setupUI];
    [self updateInfo];
    self.http = [[XSHttpHelper alloc] init];
    [[MyEventBus sharedInstance] registerSubscriber:self];
  }
  return self;
}

- (void)dealloc {
  [[MyEventBus sharedInstance] unregisterSubscriber:self];
}

- (void)setupUI {
  // Name Label
  self.nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 180, 18)];
  self.nameLabel.textColor = [UIColor whiteColor];
  self.nameLabel.font = [UIFont systemFontOfSize:14.0];
  [self addSubview:self.nameLabel];

  // IP Label
  self.ipLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 35, 180, 20)];
  [self addSubview:self.ipLabel];

  self.infoLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 55, 180, 20)];
  [self addSubview:self.infoLabel];

  // Device Type Label
  self.deviceTypeLabel =
      [[UILabel alloc] initWithFrame:CGRectMake(10, 75, 180, 30)];
  self.deviceTypeLabel.textColor = [UIColor whiteColor];
  self.deviceTypeLabel.numberOfLines = 0;
  self.deviceTypeLabel.font = [UIFont systemFontOfSize:12.0];
  [self addSubview:self.deviceTypeLabel];

  // Action Button
  self.actionButton = [UIButton buttonWithType:UIButtonTypeSystem];
  self.actionButton.frame = CGRectMake(10, 120, 70, 30);
  [self.actionButton setTitleColor:[UIColor whiteColor]
                          forState:UIControlStateNormal];
  [self.actionButton setTitleColor:[UIColor redColor]
                          forState:UIControlStateHighlighted];
  // 'rgb(113, 201, 206)'
  self.actionButton.backgroundColor = [UIColor colorWithRed:113 / 255.0
                                                      green:201 / 255.0
                                                       blue:206 / 255.0
                                                      alpha:1.0];
  // self.actionButton.layer.borderWidth = 1.0;
  // self.actionButton.layer.borderColor = [UIColor blueColor].CGColor;
  self.actionButton.layer.cornerRadius = 4.0;
  NSString *btnTitle = @"已停止";
  [self.actionButton setTitle:btnTitle forState:UIControlStateNormal];
  [self.actionButton addTarget:self
                        action:@selector(actionButtonTapped:)
              forControlEvents:UIControlEventTouchUpInside];
  [self addSubview:self.actionButton];

  // Settings Button
  self.settingsButton = [UIButton buttonWithType:UIButtonTypeSystem];
  self.settingsButton.frame = CGRectMake(90, 120, 70, 30);
  [self.settingsButton setTitleColor:[UIColor whiteColor]
                            forState:UIControlStateNormal];
  [self.settingsButton setTitleColor:[UIColor redColor]
                            forState:UIControlStateHighlighted];
  self.settingsButton.backgroundColor = [UIColor colorWithRed:113 / 255.0
                                                        green:201 / 255.0
                                                         blue:206 / 255.0
                                                        alpha:1.0];
  // self.actionButton.layer.borderWidth = 1.0;
  // self.actionButton.layer.borderColor = [UIColor blueColor].CGColor;
  self.settingsButton.layer.cornerRadius = 4.0;
  [self.settingsButton setTitle:@"刷新" forState:UIControlStateNormal];
  [self.settingsButton addTarget:self
                          action:@selector(settingsButtonTapped)
                forControlEvents:UIControlEventTouchUpInside];
  [self addSubview:self.settingsButton];

  self.infoLabel.text = @"S:0 / L:0";
  // self.center = CGPointMake(90,  self.superview.bounds.size.height - 100);
}

- (void)updateInfo {
  XSPhoneConfig *info = [XSPhoneConfig sharedInstance];
  self.nameLabel.text = [NSString stringWithFormat:@"%@", [info IPhoneName]];
  self.ipLabel.text = [NSString
      stringWithFormat:@"IP: %@", [[XSPhoneInfo sharedInstance] IPAddress]];
  self.deviceTypeLabel.text = @"unknow";
}

- (void)onEventUpdateInfo:(id)data {
  __weak typeof(self) weakSelf = self;
  if (data) {
    dispatch_async(dispatch_get_main_queue(), ^{
      NSDictionary *dic = data;
      int loadNum = 0;
      int showNum = 0;
      int r = 25;
      int g = 118;
      int b = 210;

      NSNumber *load = dic[@"loadCount"];
      if (load && ![load isEqual:[NSNull null]]) {
        loadNum = [load intValue];
      }

      NSNumber *show = dic[@"showCount"];
      if (show  && ![show isEqual:[NSNull null]]) {
        showNum = [show intValue];
      }

      NSNumber *color_r = dic[@"color_r"];
      if (color_r  && ![color_r isEqual:[NSNull null]]) {
        r = [color_r intValue];
      }

      NSNumber *color_g = dic[@"color_g"];
      if (color_g && ![color_g isEqual:[NSNull null]]) {
        g = [color_g intValue];
      }

      NSNumber *color_b = dic[@"color_b"];
      if (color_b && ![color_b isEqual:[NSNull null]]) {
        b = [color_b intValue];
      }

      self.backgroundColor = RGB(r, g, b); // RGB(85, 172, 119);
      self.infoLabel.text = [NSString stringWithFormat:@"S:%@ / L:%@", @(showNum), @(loadNum)];

    });
  }
}

- (void)onEventUpdateStatus:(id)data {
  __weak typeof(self) weakSelf = self;
  dispatch_async(dispatch_get_main_queue(), ^{
    weakSelf.deviceTypeLabel.text = [NSString stringWithFormat:@"%@", data];
  });
}

- (void)onEventUpdateRunStatus:(id)data {
  __weak typeof(self) weakSelf = self;
  dispatch_async(dispatch_get_main_queue(), ^{
    // BOOL b = data;

    NSString *btnTitle = ([data isEqual:@(YES)] ? @"运行中" : @"已停止");
    NSLog(@"onEventUpdateRunStatus: %@,%@", data, btnTitle);
    [weakSelf.actionButton setTitle:btnTitle forState:UIControlStateNormal];
  });
}
- (void)showMyToast:(NSString *)msg {
  __weak typeof(self) weakSelf = self;
  dispatch_async(dispatch_get_main_queue(), ^{
    // UIView usage
    [weakSelf makeToast:msg];
  });
}

- (void)onEventUpdateName:(id)data {
  __weak typeof(self) weakSelf = self;
  dispatch_async(dispatch_get_main_queue(), ^{
    XSPhoneConfig *info = [XSPhoneConfig sharedInstance];
    weakSelf.nameLabel.text =
        [NSString stringWithFormat:@"%@", [info IPhoneName]];
  });
}

- (void)actionButtonTapped:(UIButton *)sender {
  NSLog(@"Action button tapped");
  MyAdTask2Mangger *man = [MyAdTask2Mangger sharedInstance];
  // MyAdTaskManager *man = [MyAdTaskManager sharedInstance];
  // IPhoneHertbeat *hertBeat = [IPhoneHertbeat sharedInstance];
  NSString *status = [man toggle]; // @"已停止";
                                   /*
                                   if ([self.actionButton.titleLabel.text isEqual:@"运行中"]) {
                                       [man stop];
                                   } else {
                                       [man start];
                                       status = @"运行中";
                                   }
                                    */
  //[self.actionButton setTitle:status  forState:UIControlStateNormal];
}

- (void)settingsButtonTapped {
  NSLog(@"Settings button tapped");
  [self updateInfo];
  //[self appendLog:@"设置按钮被按下"];
}

- (void)changeBackgroundColor {
  self.backgroundColor = [UIColor colorWithRed:arc4random_uniform(256) / 255.0
                                         green:arc4random_uniform(256) / 255.0
                                          blue:arc4random_uniform(256) / 255.0
                                         alpha:1.0];
}

- (void)appendLog:(NSString *)logMessage {
  NSString *timestamp =
      [NSDateFormatter localizedStringFromDate:[NSDate date]
                                     dateStyle:NSDateFormatterNoStyle
                                     timeStyle:NSDateFormatterMediumStyle];
  NSString *fullLogMessage =
      [NSString stringWithFormat:@"%@: %@\n", timestamp, logMessage];
  self.logTextView.text =
      [self.logTextView.text stringByAppendingString:fullLogMessage];
  [self.logTextView
      scrollRangeToVisible:NSMakeRange(self.logTextView.text.length - 1, 1)];
}

- (void)detectPan:(UIPanGestureRecognizer *)panGesture {
  UIWindow *floatingWindow = (UIWindow *)panGesture.view;
  CGPoint translation = [panGesture translationInView:floatingWindow];
  floatingWindow.center = CGPointMake(floatingWindow.center.x + translation.x,
                                      floatingWindow.center.y + translation.y);
  [panGesture setTranslation:CGPointZero inView:floatingWindow];
}

@end
