import numpy as np

from easytradesdk.indicator.SimpleIndicator import SimpleIndicator


class Vroc(SimpleIndicator):

    def __init__(self):
        super(Vroc, self).__init__()

    @staticmethod
    def generate(volume_array, time_periods):

        if (volume_array is None or len(volume_array) == 0):
            return []

        _vroc_tmp_dict = {}
        for _t in range(0, len(time_periods)):
            _time_period = time_periods[_t]
            _vroc_tmp_dict[_time_period] = Vroc.calculateVROC(volume_array, _time_period)

        _vroc_list = []
        for _index in range(0, len(volume_array)):
            _vroc = Vroc()
            for t in range(0, len(time_periods)):

                _time_period = time_periods[t]
                _np_vroc_array = _vroc_tmp_dict[_time_period]
                _vroc_value = _np_vroc_array[_index]

                if _vroc_value is not None:
                    _vroc.setValue(_vroc_value, _time_period)
                else:
                    _vroc.setValue(None, _time_period)
            _vroc_list.append(_vroc)

        return _vroc_list

    @staticmethod
    def calculateVROC(volume_array, period):

        if not volume_array or len(volume_array) < period:
            return []

        result = []
        for i, v in enumerate(volume_array):
            j = i - period
            if j < 0:
                result.append(np.NAN)
            else:
                if volume_array[j] == 0:
                    result.append(0)
                else:
                    result.append((volume_array[i] - volume_array[j]) / volume_array[j] * 100)
        return result
