# coding: utf-8

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

"""
https://finance.yahoo.com/quote/YNDX/history?p=YNDX
"""


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


class FakeSource:
    weight = 50


def process(source, saver, logger):

    with open("tools/YNDX.csv") as f:
        yndx_data = f.readlines()

    query = []
    for line in yndx_data[1:]:
        parsed_data = line.strip().split(",")
        date_str = parsed_data[0]
        date = datetime.strptime(parsed_data[0], "%Y-%m-%d")
        value = parsed_data[4]
        print("date", date, int(date.timestamp()), "value", value)
        stock_value = {
            '$set': {
                'unixtime': int(date.timestamp()),
                'time': '00:00:00',
                'value': float(value),
                'lastupdate': datetime.now(),
            },
            '$setOnInsert': {
                'id': 42,
                'source': source.weight,
                'region': 0,
                'date': date_str,
            },
        }
        find_conditions = {
            'id': 42,
            'region': 0,
            'date': date_str,
        }

        query.append(UpdateOne(find_conditions, stock_value, upsert=True))
    res = saver.stocks.bulk_write(query)
    print("modified_count:", res.modified_count, "upserted_count:", res.upserted_count)


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


if __name__ == "__main__":
    main()

