from datetime import datetime, timedelta


def get_keepa_time():
    import datetime
    import numpy as np
    KEEPA_ST_ORDINAL = np.datetime64("2011-01-01", "m")
    dt = datetime.datetime.now()
    dt64 = np.datetime64(dt, 'm')
    # print(dt64 - KEEPA_ST_ORDINAL)
    return str(dt64 - KEEPA_ST_ORDINAL).replace("minutes", "").strip()


def keepa_minutes_to_time(minutes, to_datetime=True):
    """Accept an array or list of minutes and converts it to a numpy datetime array.

    Assumes that keepa time is from keepa minutes from ordinal.
    """
    import numpy as np
    KEEPA_ST_ORDINAL = np.datetime64("2011-01-01", "m")

    # Convert to timedelta64 and shift
    dt = np.array(minutes, dtype="timedelta64[m]")
    dt = dt + KEEPA_ST_ORDINAL  # shift from ordinal

    # Convert to datetime if requested
    if to_datetime:
        return dt.astype(datetime)
    return dt


def keepa_time_disposal(t_items):
    d_msg = []
    # now_today = datetime.now() + timedelta(days=1) - timedelta(days=8)
    now_today = datetime.now() + timedelta(days=1)
    d_msg.append((now_today.year-1, now_today.month, now_today.day))
    d_msg.append((now_today.year, now_today.month, now_today.day))
    msgs = ""
    for i in d_msg:
        if i[0] == datetime.now().year:
            s = "当前"
        else:
            s = "去年"
        new_time = datetime(i[0], i[1], i[2]) - timedelta(seconds=1)
        day_7 = new_time - timedelta(days=7)
        last_rank = {}
        # for k, v in t_items.items():
        #     date_tiem = keepa_minutes_to_time(k)
        #     if date_tiem <= new_time and date_tiem >= day_7:
        #         if last_rank.get(str(date_tiem).split(" ")[0]):
        #             continue
        #         else:
        #             last_rank[str(date_tiem).split(" ")[0]] = int(v)

        for k, v in t_items.items():
            date_tiem = keepa_minutes_to_time(k)
            if date_tiem <= new_time and date_tiem >= day_7:
                # last_rank[str(date_tiem)] = v
                if last_rank.get(str(date_tiem).split(" ")[0]):
                    last_rank[str(date_tiem).split(" ")[0]].append(int(v))
                else:
                    last_rank[str(date_tiem).split(" ")[0]] = [int(v)]
        ranks = {k: int(sum(v) / len(v)) for k, v in last_rank.items()}
        if ranks:
            avg_rank = int(sum(list(ranks.values())) / len(ranks))
            msgs += str(ranks).replace("{", "").replace("}", "").replace(",", "") + f" {s}排名 {avg_rank} \n"
        else:
            msgs += f" {s}排名 0 \n"
    # print(msgs)
    return msgs if "排名 0" not in msgs else ""

