import time
import copy
import torch.optim as optim
import torch.nn as nn
from torch.optim import lr_scheduler

from config import *
from visualization import train_visualization


def train_model(args, model, metric_model, data_loaders, datasets_size, criterion,
                optimizer, scheduler, num_epochs):
    # 学習開始時間の保持
    since = time.time()

    # 初期の事前学習時点でのパラメータを保存
    best_model_wts = copy.deepcopy(model.network.state_dict())
    best_metric_model_wts = copy.deepcopy(metric_model.state_dict())
    best_acc = 0.0

    loss_dict = {"train": [], "val": []}
    acc_dict = {"train": [], "val": []}

    print("embedding model - Train phase")
    print('-' * 10)
    print()

    # 定めた回数分だけ学習を繰り返す
    for epoch in range(num_epochs):
        print('Epoch {}/{}'.format(epoch + 1, num_epochs))
        print('-' * 10)

        # 各エポックでTrainingとValidationを繰り返す
        for phase in ['train', 'val']:
            # 学習時と推論時で振る舞いの違うモジュールの振る舞いを変更する
            if phase == 'train':
                # optimizer.step()
                # scheduler.step()
                model.train()  # 学習モードに変更
                # metric_model.train()
            else:
                model.eval()  # 推論モードに変更
                # metric_model.eval()

            running_loss = 0.0
            running_corrects = 0

            # 用意したデータセットで学習を繰り返す
            for data in data_loaders[phase]:

                # 入力データ(バッチサイズ分)
                inputs, labels = data

                inputs = inputs.to(DEVICE)
                labels = labels.to(DEVICE)

                # 勾配を０で初期化する
                optimizer.zero_grad()

                # forward
                outputs = model(inputs, labels)
                '''
                features = model(inputs)
                if args.metric == 'softmax':
                    outputs = metric_model(features)
                else:
                    outputs = metric_model(features, labels)
                '''

                _, preds = torch.max(outputs.data, 1)
                loss = criterion(outputs, labels)

                # 学習フェーズの時のみ，誤差逆伝播とパラメータ更新を行う
                if phase == 'train':
                    loss.backward()  # 誤差逆伝播にて勾配を求める
                    optimizer.step()  # optimizerでパラメータを更新

                # statistics
                running_loss += loss.data.item() * inputs.size(0)
                running_corrects += torch.sum(preds == labels.data)

            if phase == 'train':
                scheduler.step()

            epoch_loss = running_loss / datasets_size[phase]
            epoch_acc = running_corrects / datasets_size[phase]

            loss_dict[phase].append(epoch_loss)
            acc_dict[phase].append(epoch_acc)

            print('{} Loss: {:.4f} Acc: {:.4f}'.format(
                phase, epoch_loss, epoch_acc))

            # deep copy the model
            if phase == 'val' and epoch_acc > best_acc:
                best_acc = epoch_acc
                best_model_wts = copy.deepcopy(model.network.state_dict())
                best_metric_model_wts = copy.deepcopy(metric_model.state_dict())

        print()

    time_elapsed = time.time() - since
    print('embedding model - Training complete in {:.0f}m {:.0f}s'.format(time_elapsed // 60, time_elapsed % 60))
    print('Best val Acc: {:4f}'.format(best_acc))
    print()

    # load best model weights
    model.network.load_state_dict(best_model_wts)
    # metric_model.load_state_dict(best_metric_model_wts)

    # モデルのパラメータを保存
    if args.model_save:
        model_path = '{}/{}_{}.pth'.format(MODEL_DIR, args.network, args.metric)
        torch.save(model.network.state_dict(), model_path)

    return loss_dict, acc_dict


def embedding_model(args, model, metric_model, data_loaders, datasets_size):
    model = model.to(DEVICE)
    metric_model = metric_model.to(DEVICE)

    '''
    weights = list(map(lambda x: max(train_class_number)/x, train_class_number))
    class_weights = torch.FloatTensor(weights).to(DEVICE)
    criterion_ft = nn.CrossEntropyLoss(weight=class_weights).to(DEVICE)
    '''

    criterion_ft = nn.CrossEntropyLoss().to(DEVICE)

    # Observe that all parameters are being optimized
    optimizer_ft = optim.SGD([{'params': model.parameters()}, {'params': metric_model.parameters()}],
                             lr=0.001, momentum=0.9)

    # Decay LR by a factor of 0.1 every 7 epochs
    exp_lr_scheduler = lr_scheduler.StepLR(optimizer_ft, step_size=7, gamma=0.1)

    loss, acc = train_model(args, model, metric_model, data_loaders, datasets_size, criterion_ft,
                            optimizer_ft, exp_lr_scheduler, num_epochs=args.epochs)

    if args.gui:
        train_visualization(loss, acc, args.epochs)
