//
//  MKRViewController.m
//  MKRRadioManager
//
//  Created by yyqxiaoyin on 04/15/2019.
//  Copyright (c) 2019 yyqxiaoyin. All rights reserved.
//

#import "MKRViewController.h"
#import "MKRPlayControlViewController.h"

@interface MKRViewController ()

@property (nonatomic, strong)UITableView *tableView;

@property (nonatomic, strong)NSMutableArray *dataSource;

@end

@implementation MKRViewController

- (IBAction)refresh:(UIBarButtonItem *)sender {
    [self.dataSource removeAllObjects];
    [self searchDevice];
}

- (void)searchDevice{
    [_MKRWIFIDeviceManager searchDeviceWithSearchTime:20 timeBlock:^(NSInteger time, NSArray *devices) {
        if (![self.dataSource isEqualToArray:devices]) {
            self.dataSource = devices.mutableCopy;
            [self.tableView reloadData];
        }
    }];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    [self.view addSubview:self.tableView];
    [[MKRWIFIDeviceManager shareManager] startUpnp];
    [self searchDevice];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];

    MKRUPnPDevice *device = self.dataSource[indexPath.row];
    cell.textLabel.text = device.deviceName;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    MKRPlayControlViewController *vc = [[MKRPlayControlViewController alloc] initWithDevice:self.dataSource[indexPath.row]];
    [self.navigationController pushViewController:vc animated:YES];
}

- (NSMutableArray *)dataSource {
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}

@end
