import os
import argparse

import glob
import numpy as np
from tqdm import tqdm
from preprocess import preprocess, postprocess, evaluate


class WrapRunner(object):

    def __init__(self, runner, rbo_mode, id=None):
        self.runner = runner
        self.rbo_mode = rbo_mode
        self.id = id
    
    def __call__(self, *args):
        if self.rbo_mode:
            inputs = list(args)
            for i in range(len(inputs)):
                if not isinstance(inputs[i], np.ndarray):
                    inputs[i] = inputs[i].numpy()
            outs = self.runner.inference(self.id, inputs)
            if isinstance(outs, list) and len(outs) == 1:
                return outs[0]
            return outs
        else:
            outs = self.runner.run(*args, as_numpy=True)
            return outs

    def close(self):
        if self.rbo_mode:
            self.runner.remove_model(self.id)


def init_runner(args):
    suffix = os.path.splitext(args.model_file)[1]
    print(f"INFO: Load model from {args.model_file}")
    if suffix == '.sg':
        import rbcc
        from rbcc.backend.runner import SGRunner
        sg = rbcc.load_sg(args.model_file)
        device = f"cuda:{args.device_id}" if args.device_id >= 0 else "cpu"
        runner = SGRunner(sg, device=device, gc_collect=True)
        return WrapRunner(runner, False)
    elif suffix == '.rbo':
        from rboexec.core.client import GRPCClient
        client = GRPCClient(os.environ['CAISA_REMOTE_IP'], int(os.environ['CAISA_REMOTE_PORT']))
        id = client.upload_model(model_path=os.path.abspath(args.model_file), device_id=args.device_id)
        return WrapRunner(client, True, id)
    else:
        raise ValueError(f"excepted .sg or .rbo file, not {suffix}")


def generate_test_dataset(args, transform):
    for image_path in glob.glob(os.path.join(args.data, 'images', '*', '*.jpg')):
        if not image_path.endswith('.jpg'):
            continue
        img, meta = transform(image_path, with_meta=True, input_size=[640, 640])
        yield img, meta


def main(args):
    print("INFO: Init Runner.")
    runner = init_runner(args)

    print("INFO: Load dataset.")
    val_loader = generate_test_dataset(args, preprocess)
    gt_file = os.path.join(args.data, 'ground_truth')
    event_list = sorted(os.listdir(os.path.join(args.data, 'images')))

    # 开始进行评价
    print("INFO: Start inference.")
    num_samples = args.eval_nums if args.eval_nums is not None else 3226
    pbar = tqdm(desc=f"Eval in Wider-Face", unit='img', total=num_samples)
    result = {event: {} for event in event_list}
    for index, (img, img_meta) in enumerate(val_loader):
        if index == args.eval_nums:
            break
        pred = runner(img)[0]
        boxes = postprocess(pred, img_meta, conf_thres=args.conf)
        event_name = img_meta['event_name']
        image_name = img_meta['image_name']
        result[event_name][image_name] = boxes
        pbar.update(1)
        
    runner.close()
    evaluate(result, gt_file)


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('model_file', type=str, help='rbo or sg file path.')
    parser.add_argument('--data', type=str, default=None, help='dataset dir.')
    parser.add_argument('--device-id', type=int, default=0, help="device id.")
    parser.add_argument('--eval-nums', type=int, help="The number of data sets that need to be verified.")
    parser.add_argument('--conf', type=float, default=0.01, help="The value of nms score threshold.")
    main(parser.parse_args())
