#!/usr/bin/env python
# -*- coding: utf-8 -*-
from datetime import datetime
import shelve
import yaml

from . import questions
from . import outputs


class LastRun(object):
    def __init__(self, path):
        store = shelve.open(path)
        try:
            self.last_run = store['last_run']
        except KeyError:
            self.last_run = datetime.fromtimestamp(0)
        store.close()

    def update(self, last_run):
        self.last_run = last_run
        store = shelve.open(path)
        store['last_run'] = last_run
        store.close()

    def __repr__(self):
        return '<%s: %s>' % (self.__class__.__name__, self.last_run)


class ConfigHandler(object):
    @classmethod
    def from_paths(cls, config_path, last_run_path):
        try:
            with open(config_path, 'r') as c:
                config = c.read()
        except IOError:
            config = ''

        last_run = LastRun(last_run_path)

        return cls(config, last_run)

    def __init__(self, config_text, last_run):
        self.config = yaml.safe_load(config_text) or {}

        # dehydrate questions
        self.questions = map(
            self.parse_question, self.config.get('questions', [])
        )
        self.outputs = map(
            self.parse_output, self.config.get('outputs', [])
        )
        self.last_run = last_run

    def parse_question(self, question):
        unit = question.values()[0].get('unit', 'number')
        units = {
            'hours': questions.HoursQuestion,
            'rating': questions.RatingQuestion,
            'number': questions.NumberQuestion,
            'yesno': questions.YesNoQuestion,
        }
        return units[unit](question)

    def parse_output(self, output):
        key = output.keys()[0]

        return {
            'stdout': outputs.StdoutOutput,
        }[key](**output.values()[0])

@@ -193,24 +193,49 @@
 elf, path):%0A
+        self.path = path%0A
         stor
@@ -260,65 +260,110 @@
 th)%0A
-   
+%0A
     
- try:%0A            self.last_run = store%5B'last_run'
+def last_run(self, key):%0A        s = shelve.open(self.path)%0A        try:%0A            return s%5Bkey
 %5D%0A  
@@ -397,31 +397,22 @@
         
-self.last_run =
+return
  datetim
@@ -430,37 +430,54 @@
 tamp(0)%0A        
-store
+finally:%0A            s
 .close()%0A%0A    de
@@ -488,23 +488,17 @@
 date
-(self, 
+_
 last_run
 ):%0A 
@@ -497,43 +497,27 @@
 _run
-):%0A        self.last_run = last_run
+(self, key, value):
 %0A   
@@ -514,36 +514,32 @@
 alue):%0A        s
-tore
  = shelve.open(p
@@ -533,24 +533,29 @@
 shelve.open(
+self.
 path)%0A      
@@ -560,45 +560,66 @@
     
-store%5B'last_run'%5D = last_run%0A
+try:%0A            s%5Bkey%5D = value%0A        finally:%0A 
         
 stor
@@ -614,21 +614,20 @@
         
-store
+   s
 .close()
@@ -711,24 +711,20 @@
 _, self.
-last_run
+path
 )%0A%0A%0Aclas

update lastrun to accept keys