//
//  HWSearchBar.m
//  双子星云手机
//
//  Created by 余衡武 on 2022/3/9.
//

#import "HWSearchBar.h"

@interface HWSearchBar () <UITextFieldDelegate>


@end

@implementation HWSearchBar

+ (instancetype)shareInstance {
    return [[NSBundle mainBundle] loadNibNamed:@"HWSearchBar" owner:self options:nil].firstObject;
}

- (void)awakeFromNib {
    [super awakeFromNib];
    
    [self drawView];
}

- (void)drawView {
    
    self.bgView.backgroundColor = HWFFFFFF10Color;
    self.bgView.layer.cornerRadius = 10;
    self.bgView.layer.masksToBounds = YES;
    
    self.searchImageView.hidden = self.textField.text.length != 0;
    self.searchPlaceHolder.hidden = self.textField.text.length != 0;
    [self.searchPlaceHolder setText:NSLocalizedString(@"Search_or_type_in_the_URL",nil)];
    
    [self.textField addObserver:self forKeyPath:@"text" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
    
    self.textField.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.textField.returnKeyType = UIReturnKeySearch;
    [self.textField addTarget:self action:@selector(textDidChange:) forControlEvents:UIControlEventEditingChanged];
    self.textField.delegate = self;
    self.textField.textColor = HWFFFFFFColor;
}

#pragma mark KVO
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    
    if ([keyPath isEqualToString:@"text"]) {
        
        self.searchImageView.hidden = self.textField.text.length != 0;
        self.searchPlaceHolder.hidden = self.textField.text.length != 0;
        
        if (self.textField.text.length == 0) {
            self.textField.placeholder = NSLocalizedString(@"Search_or_type_in_the_URL",nil);
        }
    }
}

#pragma mark UITextFieldDelegate
- (void)textFieldDidBeginEditing:(UITextField *)textField {
    self.searchImageView.hidden = YES;
    self.searchPlaceHolder.hidden = YES;
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
//    HLog(@"搜索或加载网页");
    self.searchImageView.hidden = textField.text.length != 0;
    self.searchPlaceHolder.hidden = textField.text.length != 0;
}


- (BOOL)textFieldShouldReturn:(UITextField *)textField {
//    HLog(@"搜索");
    [self.textField endEditing:YES];
    
    if ([_delegate respondsToSelector:@selector(searchBarWithText:)]) {
        [_delegate searchBarWithText:textField.text];
    }
    
    return YES;
}

- (void)textDidChange:(UITextField*)textField{
    if ([_delegate respondsToSelector:@selector(searchBarChangeText:)]) {
        [_delegate searchBarChangeText:textField.text];
    }
}

@end
