from nile.api.v1 import (
    Record,
    datetime as nd
)

import datetime


def days_ago_str(days):
    return (datetime.date.today() - datetime.timedelta(days)).isoformat()


def created_history_item(created_at):
    return {'operation': 'reveal', 'modifiedAt': created_at}


def create_feedback_record(created_at, workflow, source, type, resolved_at=None):
    def format_datetime(time_iso_str):
        return '%s %s.000000+03' % (days_ago_str(1), time_iso_str)

    if len(created_at) == 8:
        created_at = format_datetime(created_at)

    if workflow == 'feed':
        workflow = 'feedback'
    assert workflow in ('feedback', 'task')

    if resolved_at is not None and len(resolved_at) == 8:
        resolved_at = format_datetime(resolved_at)

    record_dict = {
        'type' : type,
        'source' : source,
        'workflow' : workflow,
        'history' : [created_history_item(created_at)],
        'created_at' : created_at,
        'resolved_at' : resolved_at
    }

    return Record.from_dict(record_dict)
