
import json
from datetime import datetime, timedelta
from os.path import expanduser, exists

STAMPS_FILE = expanduser('~/.workstamps.json')
DATE_FORMAT = '%Y-%m-%d %H:%M:%S'


class Stamper(object):

    def __init__(self, stamps_file=STAMPS_FILE):
        self.stamps_file = STAMPS_FILE
        self.ensure_stamps_file()
        self.stamps = []

    def ensure_stamps_file(self):
        if not exists(self.stamps_file):
            with open(self.stamps_file, 'w') as stamps_file:
                stamps_file.write('')

    def load_stamps(self):
        with open(self.stamps_file, 'r') as stamps_file:
            try:
                self.stamps = json.load(stamps_file)
            except ValueError:
                self.stamps = []

    def save_stamps(self):
        with open(self.stamps_file, 'w') as stamps_file:
            json.dump(self.stamps, stamps_file, indent=4)

    def stamp(self, start, end, customer, action):
        self.stamps.append({
            'start': start,
            'end': end,
            'customer': customer,
            'action': action,
        })

    def last_stamp(self):
        if not self.stamps:
            return None
        return self.stamps[-1]

    def worktime(self, start, end):
        worktime = (datetime.strptime(end, DATE_FORMAT) -
                    datetime.strptime(start, DATE_FORMAT))
        return worktime.seconds

    def customers(self):
        customers = []
        for stamp in self.stamps:
            if stamp['customer'] not in customers:
                customers.append(stamp['customer'])
        customers.remove(None)
        return customers

    def total_by_customer(self, customer):
        total = 0
        for stamp in self.stamps:
            if stamp['customer'] == customer:
                total += self.worktime(stamp['start'], stamp['end'])
        total = timedelta(seconds=total)
        return str(total)

    def totals(self):
        totals = {}
        for customer in self.customers():
            totals[customer] = self.total_by_customer(customer)
        return totals

    def details_by_customer(self, customer):
        details = {}
        totals = {}
        for stamp in self.stamps:
            if stamp['customer'] == customer:
                start_day = stamp['start'].split(' ')[0]
                if start_day not in details:
                    details[start_day] = []
                if start_day not in totals:
                    totals[start_day] = 0
                worktime = self.worktime(stamp['start'], stamp['end'])
                details[start_day].append(
                    ' -> %(worktime)s %(customer)s %(action)s' % {
                        'worktime': str(timedelta(seconds=worktime)),
                        'customer': stamp['customer'],
                        'action': stamp['action']
                    })
                totals[start_day] += worktime
        for day in totals:
            totals[day] = str(timedelta(seconds=totals[day]))
        return details, totals
