import logging as log
import datetime as dt
import time
from google.appengine.ext import ndb
from google.appengine.api import mail
from models import Run, Q
from rl import RL
from binary import Binary
from pprint import pprint


class Main():

    def __init__(self, auto_login=True):
        log.info('Main init started')
        self.binary = Binary(auto_login)
        self.rl = RL()
        self.loadQ()
        log.info('Main init ended')


    def loadQ(self):
        log.info('Q loading...')

        q_key = ndb.Key(Q, 'main')
        self.q = q_key.get()
        if not self.q:
            self.q = Q(key=q_key)

        # validate properties
        if not self.q.data:
            self.q.data = {}
        if not self.q.visits:
            self.q.visits = {}
            runs = Run.query().fetch()
            for run in runs:
                if run.getState() not in self.q.visits:
                    self.q.visits[run.getState()] = 0
                self.q.visits[run.getState()] += 1

        log.info('Q loaded {0}'.format(len(self.q.data)))


    def saveQ(self):
        log.info('Q saving...')
        self.q.put()
        log.info('Q saved {0}'.format(len(self.q.data)))


    def new(self):
        '''Create new iteration'''
        log.info('Main new started')

        currency, time_frame, trade_base, trade_aim = self.rl.selectNew(self.q)
        run_key = ndb.Key('Run', str(dt.datetime.utcnow()))
        run = Run(
            key=run_key,
            currency=currency,
            time_frame=time_frame,
            trade_base=trade_base,