import os
import os.path as osp
import glob
import logging
import numpy as np
import cv2
import torch
from PIL import Image

import utils.util as util
import data.util as data_util
from models import create_model

import os.path as osp
import logging
import time
import argparse
from collections import OrderedDict

import configs.options as option
import utils.util as util
from data.util import bgr2ycbcr
from data import create_dataset, create_dataloader
from models import create_model

import time

#### options
parser = argparse.ArgumentParser()
parser.add_argument('-opt', type=str, required=True, help='Path to options YMAL file.',default='./configs/test/SDSD_indoor_event.yml')
opt = option.parse(parser.parse_args().opt, is_train=False)
opt = option.dict_to_nonedict(opt)


def main():
    save_imgs = True
    model = create_model(opt)
    save_folder = './result/{}'.format(opt['name'])
    GT_folder = osp.join(save_folder, 'images/GT_sd')
    output_folder = osp.join(save_folder, 'images/output_sd')
    input_folder = osp.join(save_folder, 'images/input_sd')

    output_folder2 = osp.join(save_folder, 'images/output_d')
    input_folder2 = osp.join(save_folder, 'images/input_d')
    util.mkdirs(save_folder)
    util.mkdirs(GT_folder)
    util.mkdirs(output_folder)
    util.mkdirs(input_folder)
    util.mkdirs(output_folder2)
    util.mkdirs(input_folder2)

    print('mkdir finish')

    util.setup_logger('base', save_folder, 'test', level=logging.INFO, screen=True, tofile=True)
    logger = logging.getLogger('base')
    for phase, dataset_opt in opt['datasets'].items():

        #----------------------------------------------------------
        if phase=='val2' or phase=='val3':
            val_set = create_dataset(dataset_opt)
            val_loader = create_dataloader(val_set, dataset_opt, opt, None)
            print(len(val_loader))


            pbar = util.ProgressBar(len(val_loader))
            psnr_rlt = {}  # with border and center frames
            psnr_rlt_avg = {}
            psnr_total_avg = 0.

            ssim_rlt = {}  # with border and center frames
            ssim_rlt_avg = {}
            ssim_total_avg = 0.

            for val_data in val_loader:
                folder = val_data['folder'][0]
                idx_d = val_data['idx']
                if psnr_rlt.get(folder, None) is None:
                    psnr_rlt[folder] = []

                if ssim_rlt.get(folder, None) is None:
                    ssim_rlt[folder] = []
                model.feed_data(val_data)

                model.test()
                visuals = model.get_current_visuals()
                rlt_img = util.tensor2img(visuals['rlt'])  # uint8
                gt_img = util.tensor2img(visuals['GT'])  # uint8

                mid_ix = dataset_opt['N_frames'] // 2
                input_img = util.tensor2img(visuals['LQ'][mid_ix])
                if save_imgs:
                    try:
                        tag = '{}.{}'.format(val_data['folder'], idx_d[0].replace('/', '-'))
                        rlt_img=cv2.cvtColor(rlt_img,cv2.COLOR_BGR2RGB)
                        gt_img=cv2.cvtColor(gt_img,cv2.COLOR_BGR2RGB)
                        input_img=cv2.cvtColor(input_img,cv2.COLOR_BGR2RGB)
                        cv2.imwrite(osp.join(output_folder, '{}.png'.format(tag)), rlt_img)
                        cv2.imwrite(osp.join(GT_folder, '{}.png'.format(tag)), gt_img)
                        cv2.imwrite(osp.join(input_folder, '{}.png'.format(tag)), input_img)

                    except Exception as e:
                        print(e)
                        import ipdb; ipdb.set_trace()

                # calculate PSNR
                psnr = util.calculate_psnr(rlt_img, gt_img)
                psnr_rlt[folder].append(psnr)

                ssim = util.calculate_ssim(rlt_img, gt_img)
                # ssim = 0
                ssim_rlt[folder].append(ssim)

                pbar.update('Test {} - {}'.format(folder, idx_d))
            for k, v in psnr_rlt.items():
                psnr_rlt_avg[k] = sum(v) / len(v)
                psnr_total_avg += psnr_rlt_avg[k]

            for k, v in ssim_rlt.items():
                ssim_rlt_avg[k] = sum(v) / len(v)
                ssim_total_avg += ssim_rlt_avg[k]

            psnr_total_avg /= len(psnr_rlt)
            ssim_total_avg /= len(ssim_rlt)
            log_s = '# Validation # PSNR: {:.2f}:'.format(psnr_total_avg)
            for k, v in psnr_rlt_avg.items():
                log_s += ' {}: {:.2f}'.format(k, v)
            logger.info(log_s)

            log_s = '# Validation # SSIM: {:.4f}:'.format(ssim_total_avg)
            for k, v in ssim_rlt_avg.items():
                log_s += ' {}: {:.4f}'.format(k, v)
            logger.info(log_s)

            psnr_all = 0
            psnr_count = 0
            for k, v in psnr_rlt.items():
                psnr_all += sum(v)
                psnr_count += len(v)
            psnr_all = psnr_all * 1.0 / psnr_count
            print(psnr_all)

            ssim_all = 0
            ssim_count = 0
            for k, v in ssim_rlt.items():
                ssim_all += sum(v)
                ssim_count += len(v)
            ssim_all = ssim_all * 1.0 / ssim_count
            print(ssim_all)


        #----------------------------------------------------------
        elif phase=='val':
            val_set = create_dataset(dataset_opt)
            val_loader = create_dataloader(val_set, dataset_opt, opt, None)
            print(len(val_loader))


            pbar = util.ProgressBar(len(val_loader))
            niqe_rlt = {}  # with border and center frames
            niqe_rlt_avg = {}
            niqe_total_avg = 0.


            for val_data in val_loader:
                folder = val_data['folder'][0]
                idx_d = val_data['idx']
                if niqe_rlt.get(folder, None) is None:
                    niqe_rlt[folder] = []
                model.feed_data2(val_data)

                model.test()
                visuals = model.get_current_visuals2()
                rlt_img = util.tensor2img(visuals['rlt'])  # uint8
                # gt_img = util.tensor2img(visuals['GT'])  # uint8

                mid_ix = dataset_opt['N_frames'] // 2
                input_img = util.tensor2img(visuals['LQ'][mid_ix])
                if save_imgs:
                    try:
                        tag = '{}.{}'.format(val_data['folder'], idx_d[0].replace('/', '-'))
                        rlt_img=cv2.cvtColor(rlt_img,cv2.COLOR_BGR2RGB)
                        # gt_img=cv2.cvtColor(gt_img,cv2.COLOR_BGR2RGB)
                        input_img=cv2.cvtColor(input_img,cv2.COLOR_BGR2RGB)
                        cv2.imwrite(osp.join(output_folder2, '{}.png'.format(tag)), rlt_img)
                        # cv2.imwrite(osp.join(GT_folder, '{}.png'.format(tag)), gt_img)
                        cv2.imwrite(osp.join(input_folder2, '{}.png'.format(tag)), input_img)

                    except Exception as e:
                        print(e)
                        import ipdb; ipdb.set_trace()
                # calculate niqe
                niqe = util.calculate_niqe(rlt_img)
                niqe_rlt[folder].append(niqe)


                pbar.update('Test {} - {}'.format(folder, idx_d))
            # print(niqe_rlt)
            for k, v in niqe_rlt.items():
                niqe_rlt_avg[k] = sum(v) / len(v)
                niqe_total_avg += niqe_rlt_avg[k]


            # print(niqe_total_avg)
            niqe_total_avg /= len(niqe_rlt)
            log_s = '# Validation # NIQE: {:.2f}:'.format(niqe_total_avg)
            for k, v in niqe_rlt_avg.items():
                log_s += ' {}: {:.2f}'.format(k, v)
            logger.info(log_s)


            niqe_all = 0
            niqe_count = 0
            for k, v in niqe_rlt.items():
                niqe_all += sum(v)
                niqe_count += len(v)
            niqe_all = niqe_all * 1.0 / niqe_count
            print(niqe_all)


if __name__ == '__main__':
    main()
