# /usr/bin/env python
# -*- coding: UTF-8 -*-l
import numpy as np


def voltDipReg(data, ctnum):
    if ctnum == 3:
        datalen = len(data["ua"])
        cycleNum = int(np.floor(datalen / 80))
        ampua = [max(data["ua"][i * 80:(i + 1) * 80]) for i in range(cycleNum)]
        ampub = [max(data["ub"][i * 80:(i + 1) * 80]) for i in range(cycleNum)]
        ampuc = [max(data["uc"][i * 80:(i + 1) * 80]) for i in range(cycleNum)]
        maxua = max(ampua)
        minua = min(ampua)
        interua = (maxua - minua) / 4
        splitDict = {"0": [], "1": [], "2": []}
        for each in ampua:
            for i in range(3):
                if each > minua + i * interua and each < minua + (i + 1) * interua:
                    splitDict[str(i)].append(each)
        splitLen = {}
        for eachkey in splitDict.keys():
            splitLen[eachkey] = len(splitDict[eachkey])
        maxlenkey = max(splitLen, key=splitLen.get)
        if splitLen[maxlenkey] < 0.1:
            return 0
        virtual = np.sum(splitDict[maxlenkey]) / splitLen[maxlenkey]
        flag = 0
        if min(ampua)<0.9*virtual or min(ampub)<0.9*virtual or min(ampuc)<0.9*virtual:
            flag=1
    else:
        datalen = len(data["uab"])
        cycleNum = int(np.floor(datalen / 80))
        ampuab = [max(data["uab"][i * 80:(i + 1) * 80]) for i in range(cycleNum)]
        ampubc = [max(data["ubc"][i * 80:(i + 1) * 80]) for i in range(cycleNum)]
        maxua = max(ampuab)
        minua = min(ampuab)
        interua = (maxua - minua) / 4
        splitDict = {"0": [], "1": [], "2": []}
        for each in ampuab:
            for i in range(3):
                if each > minua + i * interua and each < minua + (i + 1) * interua:
                    splitDict[str(i)].append(each)
        splitLen = {}
        for eachkey in splitDict.keys():
            splitLen[eachkey] = len(splitDict[eachkey])
        maxlenkey = max(splitLen, key=splitLen.get)
        if splitLen[maxlenkey] < 0.1:
            return 0
        virtual = np.sum(splitDict[maxlenkey]) / splitLen[maxlenkey]
        flag = 0
        if min(ampuab)<0.9*virtual or min(ampubc)<0.9*virtual:
            flag=1
    return flag