import copy
import time
import logging
import pandas as pd
from queue import Queue
from func_timeout import func_set_timeout
from sqlalchemy.exc import OperationalError
from func_timeout.exceptions import FunctionTimedOut
# useful for handling different item types with a single interface
from amazon_spider.utils.common import is_internet_available
from amazon_spider.db.mysql_db import df_to_sql, get_country_engine
from amazon_spider.db.pg_db import get_pg_country_engine, get_14pg_country_engine


class AmazonRealResultsSpiderPipeline:
    def __init__(self, site):
        self.site = site
        self.q_dict = {
            "error_queue": Queue(),
        }
        self.num = 80
        self.img_num = 50

    @classmethod
    def from_crawler(cls, crawler):
        return cls(
            site=crawler.spider.site
        )

    @func_set_timeout(300)
    def df_to_sql(self, table_name, df, site="us", db="mysql"):
        try:
            if db == "mysql":
                if is_internet_available():
                    e = get_country_engine(site)
                    df.to_sql(name=table_name, con=e, if_exists='append', index=False)
                    e.dispose()
                    return True
                else:
                    return False
            elif db == "pg":
                if is_internet_available():
                    e = get_pg_country_engine(site)
                    df.to_sql(name=table_name, con=e, if_exists='append', index=False)
                    e.dispose()
                    return True
                else:
                    return False
            elif db == "pg14":
                if is_internet_available():
                    e = get_14pg_country_engine(site)
                    df.to_sql(name=table_name, con=e, if_exists='append', index=False)
                    e.dispose()
                    return True
                else:
                    return False
        except OperationalError as e:
            return False

    @func_set_timeout(100)
    def df_read_sql(self, find_sql, site="us", db="mysql"):
        if db == "mysql":
            e = get_country_engine(site)
            spider_complete = pd.read_sql(find_sql, con=e)
            e.dispose()
            return spider_complete
        elif db == "pg":
            e = get_pg_country_engine(site)
            spider_complete = pd.read_sql(find_sql, con=e)
            e.dispose()
            return spider_complete
        elif db == "pg14":
            e = get_14pg_country_engine(site)
            spider_complete = pd.read_sql(find_sql, con=e)
            e.dispose()
            return spider_complete

    def save_db(self, table, df, site, db):
        # 入库报错重试
        while True:
            try:
                if df_to_sql(table, df, site=site, db=db):
                    logging.info(
                        f"更新 {db} 数据库 {table} -----{df.shape}---------{df.head()} {list(df.values)[0]}")
                    break
                else:
                    logging.info(f"更新 {db} 数据库 {table} -----失败")
                    continue
            except OperationalError as e:
                logging.info(f"更新 {db} 数据库 {table} 失败  连接错误{e}")
                continue
            except FunctionTimedOut as e:
                logging.info(
                    f"更新 {db} 数据库 {table} -超时-{e}---{df.shape}---------{df.head()}")
                continue

    @func_set_timeout(300)
    def up_del_dis(self, sql, data=None, site="us", db="mysql"):
        if db == "mysql":
            e = get_country_engine(site)
        elif db == "pg":
            e = get_pg_country_engine(site)
        elif db == "pg14":
            e = get_14pg_country_engine(site)
        try:
            if not is_internet_available():
                return False
            with e.connect() as conn:
                if data != None:
                    if data:
                        conn.execute(sql, data)
                else:
                    conn.execute(sql)
                e.dispose()
                # conn.commit()
                # conn.close()
                return True
        except OperationalError as e:
            logging.info(f"error sql is {sql}")
            return False

    def up_del_db(self, sql, data=None, site="us", db="mysql"):
        if 'delete' in sql.lower():
            sql_msg = "delete"
            msg = ""
        elif 'insert' in sql.lower():
            sql_msg = "insert"
            msg = ""
        else:
            sql_msg = "update"
            msg = ""
        count = 0
        while True:
            try:
                if is_internet_available():
                    if sql_msg == "delete" and f"_self_asin_detail_{time.gmtime().tm_year}" in sql:
                        count += 1
                        logging.info(f"delete us_self_asin_detail_{time.gmtime().tm_year} 错误次数 +1")
                    if count >= 5:
                        logging.info(f"delete count >= 5")
                        break
                    if self.up_del_dis(sql, data=data, site=site, db=db):
                        logging.info(f"{sql_msg} {db} data ok ^_^ -----{len(data or []) or sql}---------{[][0:5] if data is None else data[0:5]}")
                        break
                    else:
                        time.sleep(3)
                        logging.info(
                            f"{sql_msg} {db} data error T_T --> {len(data or []) or sql}---------{[][0:5] if data is None else data[0:5]}")
                        continue
                else:
                    time.sleep(3)
                    logging.info(
                        f"{sql_msg} {db} data network error T_T --> {len(data or []) or sql}---------{[][0:5] if data is None else data[0:5]}")
                    continue
            except FunctionTimedOut as e:
                time.sleep(3)
                logging.info(f"{sql_msg} {db} data time out T_T --> {e}----{len(data or []) or sql}---------{[][0:5] if data is None else data[0:5]}")
                continue

    def site_dis(self, x):
        sites = {
            "us": "Amazon.com",
            "uk": "Amazon.co.uk",
            "de": "Amazon.de",
            "es": "Amazon.es",
            "it": "Amazon.it",
            "fr": "Amazon.fr",
            "mx": "Amazon.com.mx",
            "ca": "Amazon.ca",
            "nl": "Amazon.nl",
            "be": "Amazon.com.be",
            "se": "Amazon.se",
            "pl": "Amazon.pl",
            "tr": "Amazon.com.tr",
            'au': "Amazon.com.au",
        }
        return sites[x]

    def queue_consumer(self, q_size):
        for k, v in self.q_dict.items():
            if q_size == "max":
                dates = [v.get() for i in range(0, v.qsize())] if v.qsize() else []
            else:
                dates = [v.get() for i in range(0, self.num)] if v.qsize() >= self.num else []
            if dates:
                df = pd.DataFrame(dates)
                df = copy.deepcopy(df)
                if k == "error_queue":
                    if dates:
                        # 表名需要改
                        sql_up = f"UPDATE `other_search_asin_spider` set `state`=(%s), `results`=(%s) where asin=(%s) and site=(%s);"
                        df['site'] = df.site.apply(self.site_dis)
                        up_datas = [tuple(i) for i in df.values]
                        if len(up_datas) == 1:
                            d = up_datas[0]
                        else:
                            d = up_datas
                        self.up_del_db(sql_up, d, self.site, db="mysql")
                        logging.info(f"other_search_asin_spider   {df.shape}")

    def process_item(self, item, spider):
        if item.get("finish_spider"):
            print('等待时 将队列数据存储', {k: v.qsize() for k, v in self.q_dict.items()})
            self.queue_consumer(q_size="max")
        else:
            self.q_dict.get("error_queue").put(item)
            self.queue_consumer(q_size="min")

    def close_spider(self, spider):
        x = {k: v.qsize() for k, v in self.q_dict.items()}
        logging.info(f'sleep to queue data save {x}')
        self.queue_consumer(q_size="max")
        # send_mg("hezhe", "【实时爬取进程退出】", "实时爬取进程退出")

