#! /usr/bin/env python
# -*- coding: utf-8 -*-

from os import path
import json
from komandr import command, arg, main


class db:
    _PATH = path.expanduser('~/.dudu')

    def __init__(self, path=None):
        self.path = path or self._PATH

    def __enter__(self):
        if path.exists(self.path):
            with open(self.path, 'rw') as f:
                self.todos = json.loads(f.read())
        else:
            self.todos = []
        return self.todos

    def __exit__(self, type, value, tb):
        with open(self.path, 'w') as f:
            f.write(json.dumps(self.todos))


@command
def add(task):
    with db() as todos:
        todos.append({'task': task, 'done': False})


@command
@arg('index', type=int)
def delete(index):
    with db() as todos:
        try:
            del todos[index]
        except KeyError:
            print 'Not Found'


@command
@arg('index', type=int)
def update(index, task):
    with db() as todos:
        try:
            todos[index]['task'] = task
        except KeyError:
            print 'Not Found'


@command
def list():
    with db() as todos:
        for i in range(0, len(todos)):
            print "%s %s '%s'" % (i, u'✔' if todos[i]['done'] else u'✘',
                                  todos[i]['task'])


@command
def reset():
    with db() as todos:
        todos[:] = []


def flag(index, done):
    with db() as todos:
        try:
            todos[index]['done'] = done
        except KeyError:
            print 'Not Found'


@command
@arg('index', type=int)
def done(index):
    flag(index, True)


@command
@arg('index', type=int)
def undone(index):
    flag(index, False)

main()
