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

# System modules
import json
from pathlib import Path


def guess(value):
    try:
        val = int(value)
        return val
    except:
        try:
            # float
            val = float(value)
            return val
        except:
            try:
                # list or dict
                val = json.loads(value)
                return val
            except:
                # string
                return value


# class TemplateObject(object):
#     def __init__(self, path):
#         self.path = Path("defaults")
#         self.ext = ".json"

#     @property
#     def todos(self):
#         todos = []
#         filenames = self.path.glob(f"*"+self.ext)
#         for filename in filenames:
#             card = {
#                 "filename": str(filename),
#                 "name": filename.stem,
#                 "content": self.read(filename)
#             }
#             todos.append(card)
#         return todos

#     def read(self, filename):
#         with open(filename) as f:
#             content = json.load(f)
#         return content

#     def show(self, name):
#         card = next((t for t in self.todos if t["name"] == name), None)
#         return card

#     def content(self, name):
#         return self.show(name)["content"]


class ObservationBlockObject(object):
    def __init__(self, path):
        self.path = Path(path)
        self.ext = ".json"

    @property
    def todos(self):
        todos = []
        filenames = self.path.glob(f"*"+self.ext)
        for filename in filenames:
            content = self.read(filename)
            # Workaround for templates which are not lists
            content = [content] if type(content) != list else content
            card = {
                "filename": str(filename),
                "name": filename.stem,
                "content": content
            }
            todos.append(card)
        return todos

    def read(self, filename):
        with open(filename) as f:
            #print(filename)
            content = json.load(f)
        return content

    def show(self, name):
        card = next((t for t in self.todos if t["name"] == name), None)
        return card
        # with open(card["filename"]) as f:
        #     content = json.load(f)
        # return content

    def content(self, name):
        return self.show(name)["content"]

    def create(self, name):
        self.update(name)
        return self.todos

    def update(self, name, data=[]):
        filename = self.path / (name + self.ext)
        with open(filename, "w") as f:
            json.dump(data, f, indent=4)
        return self.todos

    def delete(self, name):
        filename = self.path / (name + self.ext)
        filename.unlink()
        return self.todos
