# coding: utf-8

import json
from django.http import HttpResponse
from django.shortcuts import render
from pymongo import MongoClient, ASCENDING, DESCENDING
from bson.objectid import ObjectId
from stocks3.share.singleton import Singleton


class PlannerConnect(object, metaclass=Singleton):
    def __init__(self, connectionstring, plannerdatabase):
        self.client = MongoClient(connectionstring, readPreference='secondary')
        self.plannerdatabase = plannerdatabase
        self.sourcedata = self.client.stocksdb.sourcedata
        self.db = self.client[self.plannerdatabase]
        self.planner_config = self.db.planner
        self.planner_log = self.db.planner_log
        self.planner_lock = self.db.planner_lock

    @property
    def tasks(self):
        for t in self.planner_config.find().sort([("distribution", ASCENDING),
                                                  ("command", ASCENDING)]):
            t['id'] = t['_id']
            yield t

    def logs(self, job_id):
        for t in self.planner_log.find({"job_id": ObjectId(job_id)}).sort([("ts", DESCENDING)]).limit(10):
            t['ts'] = t['ts'].strftime("%H:%M:%S %d.%m.%Y")
            yield t


with open("../config/config.json") as configfile:
    config = json.load(configfile)
    default_planner = PlannerConnect(config["db"]["connectionstring"],
                                     "planner" if config["env"] == "testing" else "stocksdb")


def index(request):
    title = 'Stocks admin. Planner jobs'
    return render(request,
                  'index.html',
                  {
                      'title': title,
                      'tasks': default_planner.tasks,
                  })


def logs(request):
    title = 'Stocks admin. Planner job logs'
    return render(request,
                  'logs.html',
                  {
                      'title': title,
                      'logs': default_planner.logs(request.GET['job_id']),
                  })
