# -*- coding: utf-8 -*-

import datetime
import os
import re
import time

import pytz
try:
    import json
except ImportError:
    try:
        import simplejson as json
    except ImportError:
        from django.utils import simplejson as json

from twactor import cache, connection, json, log


class User(cache.CachedObject):
    
    """Get info on a twitter user."""
    
    STATUS_UPDATE_INTERVAL = 3 * 60 # 3 minutes between each status update.
    
    def __init__(self, username_or_id, *args, **kwargs):
        if isinstance(username_or_id, basestring):
            self._cache['screen_name'] = username_or_id.decode('utf-8')
        elif isinstance(username_or_id, (int, long)):
            self._cache['id'] = username_or_id
        self.profile = UserProfile(self)
    
    def __eq__(self, user):
        if not isinstance(user, (User, UserProfile)):
            return False
        elif isinstance(user, User):
            return self.username == user.username
        elif isinstance(user, UserProfile):
            return self == user.user
    
    def __repr__(self):
        return 'User(%r)' % (self._identifier,)
    
    @classmethod
    def me(cls):
        return cls(cls._connection_broker.username)
        
    def _update_cache(self):
        logger = log.getLogger('twactor.User.update')
        logger.debug('Updating cache for user %s' % (self._identifier,))
        try:
            data = self._connection_broker.get('/users/show/%s.json' % (
                self._identifier,))
        except Exception, exc:
            # TODO: implement better error handling.
            logger.error('Error fetching user info for %s' % (
                self._identifier,))
        else:
            self._cache = data
    
    @property
    def _identifier(self):
        return self._cache.get('screen_name',
            self._cache.get('id', None) or '')
    
    @property
    @cache.update_on_time(STATUS_UPDATE_INTERVAL)
    def status(self):
        status_data = self._cache['status'].copy()
        status_data['user'] = self._cache.copy()
        status_data['user'].pop('status')
        return Tweet(status_data['id'], cache=status_data
            )._with_connection_broker(self._connection_broker)
    
    @property
    @cache.update_on_key('created_at')
    def joined(self):
        dtime = datetime.datetime.strptime(self._cache['created_at'],
            '%a %b %d %H:%M:%S +0000 %Y')
        return dtime.replace(tzinfo=pytz.utc)
    
    @property
    @cache.update_on_key('utc_offset')
    def timezone(self):
        tzinfo = pytz.FixedOffset(self._cache['utc_offset'] / 60.0)
        tzinfo.dst = lambda *args: datetime.timedelta()
        return (self._cache['time_zone'], tzinfo)
    
    id = cache.simple_map('id')
    username = cache.simple_map('screen_name')
    description = cache.simple_map('description')
    location = cache.simple_map('location')
    name = cache.simple_map('name')
    protected = cache.simple_map('protected')
    url = cache.simple_map('url')
    _favourite_count = cache.simple_map('favourites_count')
    _follower_count = cache.simple_map('followers_count')
    _friend_count = cache.simple_map('friends_count')
    _status_count = cache.simple_map('statuses_count')
    _time_zone_name = cache.simple_map('time_zone')
    _time_zone_utc_offset = cache.simple_map('utc_offset')


class UserProfile(cache.CachedMirror):
    
    _mirrored_attribute = 'user'
    
    def __eq__(self, profile):
        if not isinstance(profile, (User, UserProfile)):
            return False
        elif isinstance(profile, UserProfile):
            return profile.user == self.user
        elif isinstance(profile, User):
            return profile == self.user
    
    def __repr__(self):
        return 'UserProfile(%r)' % (self.user,)
    
    bg_color = cache.simple_map('profile_background_color')
    bg_image_url = cache.simple_map('profile_background_image_url')
    bg_title = cache.simple_map('profile_background_title')
    avatar_url = cache.simple_map('profile_image_url')
    link_color = cache.simple_map('profile_link_color')
    sidebar_border_color = cache.simple_map('profile_sidebar_border_color')
    sidebar_fill_color = cache.simple_map('profile_sidebar_fill_color')
    text_color = cache.simple_map('profile_text_color')


class Tweet(cache.CachedObject):
    
    def __init__(self, id, *args, **kwargs):
        try:
            id = int(id)
        except TypeError:
            pass
        else:
            self._cache['id'] = id