//
//  StockListViewController.m
//  EugineAPISample
//
//  Created by aaab on 2023/01/24.
//

#import "OverseaSearchViewController.h"
#import "SmartChampAPI.h"
#import "IStructItemCode.h"
#import "SearchUtil.h"
#import "ComUtil.h"
#import "UITextField+Addition.h"
#import "ComboBox.h"

#define sUS     @"US"
#define sUSNYS  @"NYS"
#define sUSAMX  @"AMX"
#define sUSNAS  @"NAS"
#define sETF    @"ETF"

#define sCH     @"CN"
#define sCHSHS  @"SHS"
#define sCHSZS  @"SZS"

#define sHK     @"HK"
#define sHKHKS  @"HKS"



@interface OverseaSearchViewController () < UITableViewDelegate , UITableViewDataSource , UITextFieldDelegate , IComboBox>
{
    SmartChampAPI           *champAPI;
    NSMutableDictionary     *dicOverseaItems;
    NSArray                 *arrayDefaultItemCode;
    NSMutableArray          *arraySearchedStockItem;
    ComboBox                *nationCombo;
    ComboBox                *exchangeCombo;
    NSMutableDictionary     *dicComboItem;
    NSString                *sSearchText;
    UITableView             *itemTableView;
}
@end

@implementation OverseaSearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self.view setBackgroundColor:[UIColor whiteColor]];
    UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(20, 20, CGRectGetWidth(self.view.frame) - 40, 40)];
    [textField setDelegate:self];
    [textField setClearButtonMode:UITextFieldViewModeWhileEditing];
    [textField setAutocorrectionType:UITextAutocorrectionTypeNo];
    [textField setAutocapitalizationType:UITextAutocapitalizationTypeNone];
    [textField setReturnKeyType:UIReturnKeySearch];
    [textField addNumericAccessory:NO];
    [ComUtil makeRoundView:textField radius:4 width:1 bordercolor:[UIColor lightGrayColor]];
    [textField addTarget:self action:@selector(onChangedValue:) forControlEvents:UIControlEventEditingChanged];
    [self.view addSubview:textField];
    
    CGFloat widthCombo = (CGRectGetWidth(self.view.frame) - 40 - 10 ) / 2 ;
    nationCombo = [[ComboBox alloc] initWithFrame:CGRectMake(CGRectGetMinX(textField.frame), CGRectGetMaxY(textField.frame) + 10 , widthCombo, CGRectGetHeight(textField.frame))];
    [nationCombo setComboDelegate:self];
    [self.view addSubview:nationCombo];
    
    exchangeCombo = [[ComboBox alloc] initWithFrame:CGRectMake(CGRectGetMaxX(nationCombo.frame) + 10 , CGRectGetMinY(nationCombo.frame), widthCombo, CGRectGetHeight(textField.frame))];
    [exchangeCombo setComboDelegate:self];
    [self.view addSubview:exchangeCombo];
    
    CGRect tableRect = CGRectMake(0, CGRectGetMaxY(exchangeCombo.frame) + 20, CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.frame) - CGRectGetMaxY(exchangeCombo.frame) - 20);
    itemTableView = [[UITableView alloc] initWithFrame:tableRect style:UITableViewStylePlain];
    
    [self.view addSubview:itemTableView];
    [itemTableView setDataSource:self];
    [itemTableView setDelegate:self];
    
    champAPI = [SmartChampAPI instance];
    
    NSArray *arrayNation = [NSArray arrayWithObjects:sUS, sCH , sHK , nil];
    [nationCombo setKeys:arrayNation title:arrayNation];
    dicComboItem = [NSMutableDictionary dictionary];
    [dicComboItem setObject:[NSArray arrayWithObjects:sUSNYS, sUSAMX, sUSNAS, sETF, nil] forKey:arrayNation[0]];
    [dicComboItem setObject:[NSArray arrayWithObjects:sCHSHS , sCHSZS ,sETF , nil] forKey:arrayNation[1]];
    [dicComboItem setObject:[NSArray arrayWithObjects:sHKHKS, sETF, nil] forKey:arrayNation[2]];
    
    [exchangeCombo setKeys:dicComboItem[arrayNation[0]] title:dicComboItem[arrayNation[0]]];
    
    NSArray *arrayUSNYS = [champAPI getOverseasStockCodeList:sUS exchange:sUSNYS];
    NSArray *arrayUSAMX = [champAPI getOverseasStockCodeList:sUS exchange:sUSAMX];
    NSArray *arrayUSNAS = [champAPI getOverseasStockCodeList:sUS exchange:sUSNAS];
    NSArray *arrayUSETF = [champAPI getOverseasStockCodeList:sUS exchange:sETF];
    
    NSMutableDictionary *dicUS = [NSMutableDictionary dictionaryWithObjectsAndKeys:arrayUSNYS, sUSNYS , arrayUSAMX , sUSAMX , arrayUSNAS , sUSNAS , arrayUSETF , sETF , nil];
    
    NSArray *arrayCNSHS = [champAPI getOverseasStockCodeList:sCH exchange:sCHSHS];
    NSArray *arrayCNSZZ = [champAPI getOverseasStockCodeList:sCH exchange:sCHSZS];
    NSArray *arrayCNETF = [champAPI getOverseasStockCodeList:sCH exchange:sETF];
    
    NSMutableDictionary *dicCH = [NSMutableDictionary dictionaryWithObjectsAndKeys:arrayCNSHS, sCHSHS , arrayCNSZZ , sCHSZS , arrayCNETF , sETF , nil];
    
    NSArray *arrayHKHKS = [champAPI getOverseasStockCodeList:sHK exchange:sHKHKS];
    NSArray *arrayHKETF = [champAPI getOverseasStockCodeList:sHK exchange:sETF];
    
    NSMutableDictionary *dicHK = [NSMutableDictionary dictionaryWithObjectsAndKeys:arrayHKHKS, sHKHKS , arrayHKETF , sETF , nil];
    
    dicOverseaItems = [NSMutableDictionary dictionary];
    [dicOverseaItems setObject:dicUS forKey:sUS];
    [dicOverseaItems setObject:dicCH forKey:sCH];
    [dicOverseaItems setObject:dicHK forKey:sHK];
    
    arrayDefaultItemCode = [NSArray arrayWithArray:[self defaultSearchItem:[nationCombo getSelectkey] exchange:[exchangeCombo getSelectkey]]];
    arraySearchedStockItem = [NSMutableArray arrayWithArray:arrayDefaultItemCode];
    
    [self makeCloseButton];
}


- (void)makeCloseButton
{
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setFrame:CGRectMake(CGRectGetWidth(self.view.frame) - 50 , 15, 35, 35)];
    [button addTarget:self action:@selector(onCloseButton:) forControlEvents:UIControlEventTouchUpInside];
    UIImage *image = [UIImage imageNamed:@"ic_floating_close_48.png"];
    [button setImage:image forState:UIControlStateNormal];
    [button setImage:image forState:UIControlStateHighlighted];
    [self.view addSubview:button];
}

- (void)onCloseButton:(UIButton*)sender
{
    [self dismissViewControllerAnimated:YES completion:nil];
}


- (void)selectComboBox:(ComboBox*)box selectKey:(NSString*)key
{
    if (box == nationCombo){
        [exchangeCombo setKeys:dicComboItem[[box getSelectkey]] title:dicComboItem[[box getSelectkey]]];
    }
    arrayDefaultItemCode = [NSArray arrayWithArray:[self defaultSearchItem:[nationCombo getSelectkey] exchange:[exchangeCombo getSelectkey]]];
    arraySearchedStockItem = [NSMutableArray arrayWithArray:arrayDefaultItemCode];
    [itemTableView reloadData];
}

- (NSArray*)defaultSearchItem:(NSString*)nation exchange:(NSString*)exchange
{
    return [[dicOverseaItems objectForKey:nation] objectForKey:exchange];
}

- (void)dealloc
{
    champAPI = nil;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (void)onChangedValue:(UITextField*)sender
{
    [self searchItem:sender.text];
}

- (void)searchItem:(NSString*)searchText
{
    sSearchText = searchText;
    
//    if (nItemSearchType == SEARCH_TYPE_ELW || nItemSearchType == SEARCH_TYPE_ETF || nItemSearchType == SEARCH_TYPE_ETN) {
//        if (searchText != nil && [searchText length] > 0) {
//            [self defalutAllFillter];
//        }
//    }

    NSMutableArray *arraySearchedItem = nil;
    NSArray *arrayFilltered = arrayDefaultItemCode;
    
//    if (![searchText isEqualToString:@""] && searchText != nil)
//        arrayDefaultItemCode = arrayDefaultItemCode;
    
    if (searchText == nil || [searchText length] == 0) {
        arraySearchedItem = [NSMutableArray arrayWithArray:arrayFilltered];
        [itemTableView reloadData];
        return;
    }

    [arraySearchedStockItem removeAllObjects];
    arraySearchedStockItem = [NSMutableArray arrayWithArray:[SearchUtil searchTextFromArray:searchText sourceArray:arrayFilltered propertyname:@"name|||code" middleWord:NO]];
    
    [itemTableView reloadData];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (arraySearchedStockItem == nil) return 0;
    
    return [arraySearchedStockItem count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    UILabel *codelabel = nil;
    UILabel *namelabel = nil;
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
        
        
        codelabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 0, 100, CGRectGetHeight(cell.frame))];
        [codelabel setTag:1];
        [cell.contentView addSubview:codelabel];
        [codelabel setFont:[UIFont fontWithName:@"HelveticaNeue-Medium" size:13]];
        
        namelabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(codelabel.frame), 0, CGRectGetWidth(cell.frame) - CGRectGetMaxX(codelabel.frame), CGRectGetHeight(cell.frame))];
        [namelabel setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
        [namelabel setTag:2];
        [cell.contentView addSubview:namelabel];
        [namelabel setFont:[UIFont fontWithName:@"HelveticaNeue-Bold" size:13]];
    }
    
    if (codelabel == nil){
        codelabel = [cell.contentView viewWithTag:1];
    }
    
    if (namelabel == nil){
        namelabel = [cell.contentView viewWithTag:2];
    }
    
    id <IStructItemCode> item = (id <IStructItemCode>)[arraySearchedStockItem objectAtIndex:indexPath.row];
    
    [codelabel setText:[item getCode]];
    [namelabel setText:[item getName]];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    id <IStructItemCode> item = (id <IStructItemCode>)[arraySearchedStockItem objectAtIndex:indexPath.row];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"notiSearchStockItem" object:item];
    
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}


@end
