import json
import time
import redis
import logging
import sys, os
import platform
from scrapy.utils.project import get_project_settings
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(sys.path[0]))))
from amazon_spider.utils.read_db_data import ReadDb


if "Windows" == platform.system():
    print("windows")
else:
    time.tzset()

REDIS_CONF = get_project_settings().get('REDIS')


logging.basicConfig(format='%(asctime)s %(name)s %(levelname)s %(message)s',
                            level=logging.INFO)


def get_redis_client():
    client = redis.StrictRedis(**REDIS_CONF)
    return client


redis_client = get_redis_client()


def seeds(site="us"):
    seed = ReadDb(site).read_db_self_other()
    pipe_count = redis_client.zcard(f"other_self_asin_seed")
    if pipe_count:
        logging.info("队列内数据未消费完")
        return
    for name, seed in seed.groupby("site")['asin']:
        name = name.split(".")[-1]
        # priority = 1 if name in ['ca', 'mx'] else int(seed.count())
        priority = int(seed.count())
        pipe = redis_client.pipeline(transaction=False)
        print(name, seed.count())
        if name != 'jp':
            for job in seed:
                meta = {
                    "asin": job,
                    "site": name,
                    "priority": priority,
                }
                k = json.dumps(meta)
                pipe.zadd(f"other_self_asin_seed", {k: meta['priority']})
        else:
            print(f"非需要站点直接跳过{name}")
            continue
        pipe.execute()


if __name__ == '__main__':
    for i in ["us"]:
    # for i in ["us", "uk", "fr", "de", "it", "es"]:
        logging.info(f"推送{i}任务——————")
        seeds(i)
        logging.info(f"推送{i}任务完成——————")
        time.sleep(5)


# spiders = {}
# module_content = import_module(f'amazon_spider.spiders.test_redis')
# # print(module_content)
# # print(vars(module_content))
# # obj = getattr(module_content, 'TestSpider')
# for block_name, block_type in vars(module_content).items():
#     if block_name == 'TestSpider':
#         print(block_name, block_type)
#         spiders.update({block_type.name: block_type})
# print("-----")
# print(spiders)
# spider = spiders['test']().custom_settings
# seeds_generate = seeds(spider)
# count = 0
# for seed in seeds_generate:
#     try:
#         spider.push_request(seed)
#         count += 1
#     except Exception as e:
#         logging.exception(f'error push')

