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


class AmazonCommentSpiderPipeline:
    def __init__(self, site="us"):
        self.site = site
        self.comment_table_name = f"{self.site}_asin_comment"
        self.asin_table_name = selection_table_name.get(f"{self.site}_asin_variat")
        self.comment_count_table = selection_table_name.get(f"{self.site}_comment_num_table")
        self.q_dict = {
            "comment_count_queue": Queue(),
            "comment_queue": Queue(),
            "update_queue": Queue(),
        }
        self.num = 50


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

    @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} {e}")
            return False

    def up_del_db(self, sql, data=None, site="us", db="mysql"):
        if 'delete' in sql.lower():
            sql_msg = "delete"
        else:
            sql_msg = "update"
        while True:
            try:
                if self.up_del_dis(sql, data=data, site=site, db=db):
                    logging.info(f"{sql_msg} {db} 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} asin 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} time out T_T --> {e}----{len(data or []) or sql}---------{[][0:5] if data is None else data[0:5]}")
                continue

    def queue_consumer(self, q_size):
        for k, v in self.q_dict.items():
            if q_size == "max":
                if v.qsize():
                    if k == 'comment_queue':
                        datas = []
                        for i in range(0, v.qsize()):
                            datas += v.get()
                    else:
                        datas = [v.get() for i in range(0, v.qsize())]
                else:
                    datas = []
            else:
                if v.qsize() >= self.num:
                    if k == 'comment_queue':
                        datas = []
                        for i in range(0, self.num):
                            datas += v.get()
                    else:
                        datas = [v.get() for i in range(0, self.num)]
                else:
                    datas = []
            if datas:
                if k == 'comment_count_queue':
                    inset_sql = f"insert into `{self.comment_count_table}` (`parent_asin`, `comment_num`, `star`) values (%s, %s, %s) ON DUPLICATE KEY UPDATE `parent_asin` = values(`parent_asin`), `comment_num` = values(`comment_num`), `star` = values(`star`);"
                    d = datas[0] if len(datas) == 1 else datas
                    self.up_del_db(inset_sql, data=d, site=self.site, db="mysql")
                    logging.info(f"asin_comment_num {d}")
                elif k == 'update_queue':
                    sql_up = f"UPDATE `{self.asin_table_name}` set `state`=(%s), `comment_new_time`=(%s)  where `parent_asin`=(%s);"
                    d = datas[0] if len(datas) == 1 else datas
                    self.up_del_db(sql_up, data=d, site=self.site, db="mysql")
                    logging.info(f"更新评论时间及爬取状态 {self.asin_table_name} {d}")
                elif k == 'comment_queue':
                    df = pd.DataFrame(datas)
                    column_index = ['asin', 'parent_asin', 'title', 'content', 'is_vp', 'model', 'rating', 'agree_num', 'img_num', 'img_url', 'is_video', 'video_url', 'comment_url', 'user_name', 'user_img', 'country', 'user_page', 'is_earns_commissions', 'comment_time', 'page', 'star', 'vine_review_flag', 'comment_id', 'page_state']
                    df = df[column_index]
                    logging.info(f"去重前长度  {df.shape} ")
                    df.drop_duplicates(subset=["comment_id"], inplace=True)
                    logging.info(f"去重后长度 {df.shape} ")
                    logging.info(f"{df.keys()}")
                    inset_sql = f"insert into `{self.comment_table_name}` (`asin`, `parent_asin`, `title`, `content`, `is_vp`, `model`, `rating`,`agree_num`, `img_num`, `img_url`, `is_video`, `video_url`,`comment_url`, `user_name`, `user_img`, `country`, `user_page`,`is_earns_commissions`, `comment_time`, `page`, `star`, `vine_review_flag`, `comment_id`,`page_state`) values (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s) ON DUPLICATE KEY UPDATE `asin` = values(`asin`), `parent_asin` = values(`parent_asin`), `title` = values(`title`), `content` = values(`content`), `is_vp` = values(`is_vp`), `model` = values(`model`), `rating` = values(`rating`), `agree_num` = values(`agree_num`), `img_num` = values(`img_num`), `img_url` = values(`img_url`), `is_video` = values(`is_video`), `video_url` = values(`video_url`), `comment_url` = values(`comment_url`), `user_name` = values(`user_name`), `user_img` = values(`user_img`), `country` = values(`country`), `user_page` = values(`user_page`), `is_earns_commissions` = values(`is_earns_commissions`), `comment_time` = values(`comment_time`), `page` = values(`page`), `star` = values(`star`), `vine_review_flag` = values(`vine_review_flag`), `comment_id` = values(`comment_id`), `page_state` = values(`page_state`);"
                    df_data = list(list(i) for i in df.values)
                    d = df_data[0] if len(df_data) == 1 else df_data
                    self.up_del_db(inset_sql, data=d, site=self.site, db="mysql")
                    logging.info(f"入库成功--> 长度： {len(list(set(df.asin)))} asin: {list(set(df.asin))[:5]} parent_asin: {list(set(df.parent_asin))[:5]}")

    def process_item(self, item, spider):
        if item.get("finish_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")
        if item.get('save_data'):
            if item.get("items"):
                self.q_dict.get("comment_queue").put(item.get('items'))
            if item.get('update_status'):
                self.q_dict.get("update_queue").put(item.get('update_status'))
            if item.get('comment_count'):
                self.q_dict.get("comment_count_queue").put((item.get("asin"), item.get("comment_count"), item.get("star")))
        self.queue_consumer("min")

    def close_spider(self, spider):
        print(f'{self.site}  爬虫结束，存储最后 数据', {k: v.qsize() for k, v in self.q_dict.items()})
        self.queue_consumer("max")
