import logging

from seaserv import seafile_api
from seahub.api2.models import TokenV2, DESKTOP_PLATFORMS

logger = logging.getLogger(__name__)

__all__ = [
    'get_user_devices',
    'do_unlink_device',
]

def get_user_devices(username):
    devices = TokenV2.objects.get_user_devices(username)

    peer_repos_map = get_user_synced_repo_infos(username)

    for device in devices:
        if device['platform'] in DESKTOP_PLATFORMS:
            peer_id = device['device_id']
            device['synced_repos'] = peer_repos_map.get(peer_id, [])

    return devices

def get_user_synced_repo_infos(username):
    '''Return a (client_ccnet_peer_id, synced_repos_on_that_client) dict'''
    tokens = []
    try:
        tokens = seafile_api.list_repo_tokens_by_email(username)
    except:
        return {}

    def sort_by_sync_time_descending(a, b):
        if isinstance(a, dict):
            return cmp(b['sync_time'], a['sync_time'])
        else:
            return cmp(b.sync_time, a.sync_time)

    tokens.sort(sort_by_sync_time_descending, reverse=True)

    peer_repos_map = {}
    for token in tokens:
        peer_id = token.peer_id
        repo_id = token.repo_id

        if peer_id not in peer_repos_map:
            peer_repos_map[peer_id] = {}

        peer_repos_map[peer_id][repo_id] = {
            'repo_id': token.repo_id,
            'repo_name': token.repo_name,
            'sync_time': token.sync_time
        }

    ret = {}
    for peer_id, repos in peer_repos_map.iteritems():
        ret[peer_id] = sorted(repos.values(), sort_by_sync_time_descending)

    return ret

def do_unlink_device(username, platform, device_id):
    if platform in DESKTOP_PLATFORMS:
        # For desktop client, we also remove the sync tokens
        msg = 'failed to delete_repo_tokens_by_peer_id' 
        try:
            if seafile_api.delete_repo_tokens_by_peer_id(username, device_id) < 0:
                logger.warning(msg)
                raise Exception(msg)
        except:
            logger.exception(msg)
            raise

    TokenV2.objects.delete_device_token(username, platform, device_id)

@@ -7,16 +7,32 @@
  logging
+%0Aimport datetime
 %0A%0Afrom s
@@ -217,16 +217,166 @@
 ce',%0A%5D%0A%0A
+def _last_sync_time(repos):%0A    latest_sync_time = max(%5Br%5B'sync_time'%5D for r in repos%5D)%0A    return datetime.datetime.fromtimestamp(latest_sync_time)%0A%0A
 def get_
@@ -653,63 +653,252 @@
     
-device%5B'synced_repos'%5D = peer_repos_map.get(peer_id, %5B%5D
+repos = peer_repos_map.get(peer_id, %5B%5D)%0A            device%5B'synced_repos'%5D = repos%0A            if repos:%0A                device%5B'last_accessed'%5D = max(device%5B'last_accessed'%5D,%0A                                              _last_sync_time(repos)
 )%0A%0A 
@@ -2153,17 +2153,16 @@
 peer_id'
- 
 %0A       

improve client last access time in devices page