# -*- coding: utf-8 -*-

"""
Скрипт, запускающий процесс обработки данных.

"""
import logging
import json
from datetime import datetime, timedelta
from pymongo import MongoClient, InsertOne
from pprint import pprint
import sys
import statistics
sys.path.append(".")

quotes = (
    (157, 40092),
    (29629, 40092),
    (29630, 40092),
    (29631, 40092),
    (29632, 40092),
    (29633, 40092),
    (29634, 40092),
)

date_from = datetime.strptime("20.02.2022", "%d.%m.%Y")
date_to = datetime.strptime("26.07.2022", "%d.%m.%Y")


class Database:
    def __init__(self, connectionstring):
        self.client = MongoClient(connectionstring, readPreference='secondary')
        self.stocks = self.client.stocksdb.stocks


class FakeSource:
    weight = 50


def make_database_write(saver, query, on_date):
    if len(query) > 0:
        try:
            res = saver.stocks.bulk_write(query)
            print("date:", on_date.strftime("%Y-%m-%d"), "modified_count:", res.modified_count, "upserted_count:", res.upserted_count)
        except Exception as e:
            print("date:", on_date.strftime("%Y-%m-%d"), "insert error:", e)
    else:
        print("date:", on_date.strftime("%Y-%m-%d"), "skip inserts")


def process(source, db, db2, logger):
    counter = 0
    query = []

    summary_data = {}
    summary_data2 = {}

    for s in db2.stocks.find({"id": 40092, "date": {"$gt": date_from.strftime("%Y-%m-%d")}}):
        if s['date'] not in summary_data2:
            summary_data2[s['date']] = {}
        if s['date'] not in summary_data:
            summary_data[s['date']] = {}
        summary_data2[s['date']][s['region']] = s

    for s in db.stocks.find({"id": 40092, "date": {"$gt": date_from.strftime("%Y-%m-%d")}}):
        if s['date'] not in summary_data:
            summary_data[s['date']] = {}
        summary_data[s['date']][s['region']] = s

    # for v in summary_data.keys():
    #     print(v)
    # return

    on_date = date_from
    while on_date < date_to:
        on_date += timedelta(days=1)
        date_str = on_date.strftime("%Y-%m-%d")

        if date_str not in summary_data and date_str not in summary_data2:
            continue

        if len(summary_data[date_str]) == 0:
            avg_sell_value = round(statistics.mean([q['sell_value'] for q in summary_data2[date_str].values()]), 4)
            avg_value = round(statistics.mean([q['value'] for q in summary_data2[date_str].values()]), 4)
        else:
            avg_sell_value = round(statistics.mean([q['sell_value'] for q in summary_data[date_str].values()]), 4)
            avg_value = round(statistics.mean([q['value'] for q in summary_data[date_str].values()]), 4)

        for quote in quotes:
            if quote[0] not in summary_data[date_str]:
                print("setting:", date_str, quote[0], avg_value, avg_sell_value)
                quote = {
                    'id': 40092,
                    'region': quote[0],
                    'date': date_str,
                    'unixtime':int(on_date.timestamp()),
                    'time': '00:00:00',
                    'value': avg_value,
                    'sell_value': avg_sell_value,
                    'lastupdate': datetime.now(),
                    'source': source.weight,
                }
                query.append(InsertOne(quote))
        counter += 1
        if counter % 100 == 0:
            make_database_write(db, query, on_date)
            query = []

    make_database_write(db, query, on_date)


def main():
    with open("config/config.json") as c:
        config = json.load(c)
        database2 = config["db"]["connectionstring"]
        database = "prodmongo"
    logging.basicConfig(level=logging.WARNING)
    logger = logging.getLogger('IMPORT')
    db = Database(database)
    db2 = Database(database2)
    source = FakeSource()
    process(source, db, db2, logger)


if __name__ == "__main__":
    main()

