"""
channels.models
~~~~~~~~~~~~~~~

:copyright: (c) 2012 DISQUS.
:license: Apache License 2.0, see LICENSE for more details.
"""
from datetime import datetime, timedelta
from disqusapi import Paginator
from flask import session

from channels.app import app, disqusapi, schedule
from channels.oauth import api_call
from channels.utils import avatar_hash, datestr_to_datetime, from_cache, secure_avatar
from channels.views import threads, posts, users


class User:
    @classmethod
    def format(cls, user):
        return {
            'id': user['id'],
            'avatar': secure_avatar(user['avatar']['cache']),
            'name': user['username'],
            'hash': avatar_hash(user)
        }

    @classmethod
    def save(cls, user):
        result = cls.format(user)
        users.add(result, datetime.utcnow().strftime('%s.%m'))
        return result

    @classmethod
    def list(cls, offset=0, limit=100):
        return users.list(offset=offset, limit=limit)

    @classmethod
    def list_by_thread(cls, thread_id, offset=0, limit=100):
        return users.list(thread_id=thread_id, offset=offset, limit=limit)

    @classmethod
    def get_by_id(cls, user_id):
        return users.get(user_id)


class Category:
    @classmethod
    def list(cls):
        return list(disqusapi.categories.list(forum=app.config['DISQUS_FORUM'], method='GET', limit=100))

    @classmethod
    def get(cls, name):
        return cls.cache[name]

Category.cache = dict((c['title'], c) for c in from_cache(Category.list))


class Thread:
    @classmethod
    def format(cls, thread):
        return {
            'id': thread['id'],
            'title': thread['title'],
            'createdAtISO': thread['createdAt'].isoformat(),
            'category': thread['category'],
            'link': thread['link'],
            'posts': thread['posts'],
        }

    @classmethod
    def save(cls, thread):
        dt = datestr_to_datetime(thread['createdAt'])
        thread['createdAt'] = dt
        result = cls.format(thread)
        score = dt.strftime('%s.%m')
        threads.add(result, score)