import argparse
import math
from itertools import islice

import tqdm
from toygan.eval.image_plot   import save_images
from toygan.eval.profile_plot import plot_profiles
from toygan.eval.funcs        import load_eval_model_dset

def parse_eval_cmdargs():
    parser = argparse.ArgumentParser(description = 'Eval CycleGAN')

    parser.add_argument(
        'model',
        help    = 'Model to evaluate',
        metavar = 'model',
        type    = str,
    )

    parser.add_argument(
        '-e', '--ext',
        default = [ 'png', 'pdf' ],
        dest    = 'ext',
        help    = 'Plot Extension',
        type    = str,
        nargs   = '+',
    )

    parser.add_argument(
        '--epoch',
        default = None,
        dest    = 'epoch',
        help    = \
            'Checkpoint Epoch to evalute. By default will evalute the last',
        type    = int,
    )

    parser.add_argument(
        '-n',
        default = 100,
        dest    = 'n_eval',
        help    = 'Number of samples to evalute',
        type    = int,
    )

    parser.add_argument(
        '--type',
        choices = [ 'transfer', 'reco' ],
        default = 'transfer',
        dest    = 'plot_type',
        help    = 'Type of evaluation',
        type    = str,
    )

    parser.add_argument(
        '--model-state',
        choices = [ 'train', 'eval' ],
        default = 'eval',
        dest    = 'model_state',
        help    = 'Evaluate models in train or eval states',
        type    = str,
    )

    parser.add_argument(
        '--batch-size',
        default = 1,
        dest    = 'batch_size',
        help    = 'Batch size to use for evaluation',
        type    = int,
    )

    return parser.parse_args()

def eval_model(
    model, it_val, n_eval, batch_size, plotdir, plot_type, model_state, ext
):
    # pylint: disable=too-many-arguments
    steps = min(math.ceil(n_eval / batch_size), len(it_val))

    for batch_idx,batch in tqdm.tqdm(
        enumerate(islice(it_val, steps)), desc = 'Evaluation', total = steps
    ):
        model.set_input(batch)
        model.forward_nograd()

        for idx in range(len(batch[0])):
            images = { k : v[idx] for (k,v) in model.images.items() }
            index  = batch_idx * batch_size + idx

            save_images(plotdir, images, index, plot_type, model_state, ext)
            plot_profiles(plotdir, images, index, plot_type, model_state, ext)

def set_model_state(model, state):
    if state == 'train':
        model.train()
    elif state == 'eval':
        model.eval()
    else:
        raise ValueError("Unknown model state '%s'" % state)

def main():
    cmdargs = parse_eval_cmdargs()
    args, model, it_val, evaldir = load_eval_model_dset(
        cmdargs.model, cmdargs.epoch, batch_size = cmdargs.batch_size
    )

    set_model_state(model, cmdargs.model_state)

    eval_model(
        model, it_val, cmdargs.n_eval, args.config.batch_size, evaldir,
        cmdargs.plot_type, cmdargs.model_state, cmdargs.ext
    )

if __name__ == '__main__':
    main()

