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

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

"""
import logging
import json
from datetime import datetime
from pymongo import MongoClient


database = 'connectionstring'


QUOTE_TO_ID = {
    'USD': 75000,
    'EUR': 75001,
    'RUB': 75002,
    'GBP': 75003,
    'KZT': 75004,
}


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


class FakeSource:
    weight = 50


def uzs_json(source, saver, logger):
    with open("UZS.json") as f:
        data = json.load(f)
        for quote, quote_data in data.items():
            print(quote, QUOTE_TO_ID[quote], len(quote_data))
            for date, value in quote_data.items():
                # print(date)
                dt = datetime.strptime(date, "%Y-%m-%d")
                stock_value = {
                    '$set': {
                        'unixtime':int(dt.timestamp()),
                        'time': '00:00:00',
                        'value': value,
                        'lastupdate': datetime.now(),
                    },
                    '$setOnInsert': {
                        'id': QUOTE_TO_ID[quote],
                        'source': source.weight,
                        'region': 0,
                        'date': date,
                    },
                }
                find_conditions = {
                    'id': QUOTE_TO_ID[quote],
                    'region': 0,
                    'date': date,
                }
                # print(find_conditions, stock_value)
                saver.stocks.update_one(find_conditions, stock_value, upsert=True)


def high_csv(source, saver, logger):
    with open('hist.csv') as f:
        lines = f.readlines()[1:]
        for l in lines:
            l = l.strip().split(', ')
            date_dt = datetime.strptime(l[0], '%m/%d/%Y')
            date_str = datetime.strftime(date_dt, '%Y-%m-%d')
            value = l[4].replace('$', '')
            # date_str, value
            print(date_str, value)
            stock_value = {
                '$set': {
                    'unixtime':int(date_dt.timestamp()),
                    'time': '00:00:00',
                    'value': value,
                    'lastupdate': datetime.now(),
                },
                '$setOnInsert': {
                    'id': 44,
                    'source': source.weight,
                    'region': 0,
                    'date': date_str,
                },
            }
            find_conditions = {
                'id': 44,
                'region': 0,
                'date': date_str,
            }
            # saver.stocks.update_one(find_conditions, stock_value, upsert=True)
            # для прода:
            # saver.stocks.update(find_conditions, stock_value, upsert=True)


def main():
    logging.basicConfig(level=logging.DEBUG)
    logger = logging.getLogger('IMPORT')
    saver = Database(database)
    source = FakeSource()
    high_csv(source, saver, logger)

if __name__ == "__main__":
    main()

