"""
Copyright 2018 NAVER Corp.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.

3. Neither the names of Facebook, Deepmind Technologies, NYU, NEC Laboratories America
   and IDIAP Research Institute nor the names of its contributors may be
   used to endorse or promote products derived from this software without
   specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
"""
import math
import numpy as np
import time
import torch


def asHHMMSS(s):
    m = math.floor(s / 60)
    s -= m * 60
    h = math.floor(m / 60)
    m -= h * 60
    return '%d:%d:%d' % (h, m, s)


def timeSince(since, percent):
    now = time.time()
    s = now - since
    es = s / (percent)
    rs = es - s
    return '%s<%s' % (asHHMMSS(s), asHHMMSS(rs))


#######################################################################
def sent2indexes(sentence, vocab):
    def convert_sent(sent, vocab):
        return np.array([vocab[word] for word in sent.split(' ')])

    if type(sentence) is list:
        indexes = [convert_sent(sent, vocab) for sent in sentence]
        sent_lens = [len(idxes) for idxes in indexes]
        max_len = max(sent_lens)
        inds = np.zeros((len(sentence), max_len), dtype=np.int)
        for i, idxes in enumerate(indexes):
            inds[i, :len(idxes)] = indexes[i]
        return inds
    else:
        return convert_sent(sentence, vocab)


def indexes2sent(indexes, vocab, eos_tok, ignore_tok=0):
    """indexes: numpy array"""

    def revert_sent(indexes, ivocab, eos_tok, ignore_tok=0):
        toks = []
        length = 0
        indexes = filter(lambda i: i != ignore_tok, indexes)
        for idx in indexes:
            toks.append(ivocab[idx])
            length += 1
            if idx == eos_tok:
                break
        return ' '.join(toks), length

    if indexes.ndim == 1:  # one sentence
        return revert_sent(indexes, vocab, eos_tok, ignore_tok)
    else:  # dim>1
        sentences = []  # a batch of sentences
        lens = []
        for inds in indexes:
            sentence, length = revert_sent(inds, vocab, eos_tok, ignore_tok)
            sentences.append(sentence)
            lens.append(length)
        return sentences, lens


def gData(data, use_cuda):
    tensor = data
    if isinstance(data, np.ndarray):
        tensor = torch.from_numpy(data)
    if use_cuda:
        tensor = tensor.cuda()
    return tensor


def gVar(data, use_cuda):
    return gData(data, use_cuda)
