import time


def findStart(timeaircond="timeaircond", timeaircond_last="", ahead=0):
    timeaircond_last_stemp = int(
        time.mktime(time.strptime(timeaircond_last, "%Y-%m-%d %H:%M:%S")))
    timeaircond_stemp = [
        int(time.mktime(time.strptime(each_time, "%Y-%m-%d %H:%M:%S"))) for
        each_time in timeaircond]
    if ahead < len(timeaircond) - 1:
        time_substruct = [1000000 if timeaircond_stemp[
                                         each_timeaircond_stemp] - timeaircond_last_stemp <= 0 or each_timeaircond_stemp < ahead else
                          timeaircond_stemp[
                              each_timeaircond_stemp] - timeaircond_last_stemp
                          for each_timeaircond_stemp
                          in range(len(timeaircond_stemp))]
    else:
        time_substruct = [
            1000000 if timeaircond_last_stemp - timeaircond_stemp[
                each_timeaircond_stemp] <= 0 or each_timeaircond_stemp < ahead else timeaircond_last_stemp -
                                                                                    timeaircond_stemp[
                                                                                        each_timeaircond_stemp]
            for
            each_timeaircond_stemp in range(len(timeaircond_stemp))]

    index = time_substruct.index(min(time_substruct))
    return index


def aircondAnalysis(statesaircond="", statesaircond_off="", timeaircond="",
                    timeaircond_off="", eachdata_pow="", eachdata_cur="",
                    timer=""):
    timeaircond_off_chang = [each.split(" ")[1][:-3].split(":") for each in
                             timeaircond_off]
    timeaircond_off_hour = [each[0] for each in timeaircond_off_chang]

    aircondRunStages = []
    aircondRunStages.append(timeaircond[0])
    for each_off in range(1, len(timeaircond_off)):
        if int(timeaircond_off_hour[-1]) - int(
                timeaircond_off_hour[-2]) <= 2 and each_off == len(
            timeaircond_off_hour) - 1:
            aircondRunStages.append(timeaircond_off[each_off])
        if int(timeaircond_off_hour[each_off]) - int(
                timeaircond_off_hour[each_off - 1]) <= 2:
            continue
        else:
            if each_off < len(timeaircond) - 1:
                aircondRunStages.append(timeaircond_off[each_off - 1])
                findStart1 = findStart(timeaircond=timeaircond,
                                       timeaircond_last=timeaircond_off[
                                           each_off - 1], ahead=each_off)
                aircondRunStages.append(timeaircond[findStart1])
            else:
                aircondRunStages.append(timeaircond_off[each_off])

    return aircondRunStages
