from __future__ import unicode_literals, division, absolute_import
import logging

from flexget import plugin
from flexget.event import event
from flexget.utils.imdb import extract_id
from flexget.utils.cached_input import cached
from flexget.entry import Entry
from flexget.utils.soup import get_soup

log = logging.getLogger('imdb_list')
USER_ID_RE = r'^ur\d{7,8}$'


class ImdbList(object):
    """"Creates an entry for each movie in your imdb list."""

    schema = {
        'type': 'object',
        'properties': {
            'user_id': {
                'type': 'string',
                'pattern': USER_ID_RE,
                'error_pattern': 'user_id must be in the form urXXXXXXX'
            },
            'list': {'type': 'string'}
        },
        'required': ['list', 'user_id'],
        'additionalProperties': False
    }

    @cached('imdb_list', persist='2 hours')
    def on_task_input(self, task, config):
        # Create movie entries by parsing imdb list page(s) html using beautifulsoup
        log.verbose('Retrieving list: %s...' % config['list'])

        params = {'view': 'compact'}
        if config['list'] in ['watchlist', 'ratings', 'checkins']:
            url = 'http://www.imdb.com/user/%s/%s' % (config['user_id'], config['list'])
        else:
            url = 'http://www.imdb.com/list/%s' % config['list']

        log.debug('Requesting: %s' % url)
        page = task.requests.get(url, params=params)
        if page.status_code != 200:
            raise plugin.PluginError('Unable to get imdb list. Either list is private or does not exist.')

        soup = get_soup(page.text)
        # TODO: Something is messed up with the html5lib parser and imdb, have to get to our subsection without
        # recursion before doing a regular find. Repeated in the loop below as well.
        soup = soup.find('div', id='root').find('div', id='pagecontent', recursive=False)
        div = soup.find('div', class_='desc')
        if div:
            total_movie_count = int(div.get('data-size'))
        else:
            total_movie_count = 0

        if total_movie_count == 0:
            log.verbose('No movies were found in imdb list.')
            return

        entries = []
        for start_movie in xrange(1, total_movie_count + 1, 250):
            if start_movie > 250:
                params['start'] = start_movie
                page = task.requests.get(url, params=params)
                if page.status_code != 200:
                    raise plugin.PluginError('Unable to get imdb list.')
                soup = get_soup(page.text)
                # TODO: This is a hack, see above
                soup = soup.find('div', id='root').find('div', id='pagecontent', recursive=False)

            trs = soup.find_all(attrs={'data-item-id': True})
            for tr in trs:
                a = tr.find('td', class_='title').find('a')
                link = ('http://www.imdb.com' + a.get('href')).rstrip('/')
                entry = Entry()
                entry['title'] = a.string
                try:
                    year = int(tr.find('td', class_='year').string)
                    entry['title'] += ' (%s)' % year
                    entry['imdb_year'] = year
                except TypeError:
                    pass
                entry['url'] = link
                entry['imdb_id'] = extract_id(link)
                entry['imdb_name'] = entry['title']
                entries.append(entry)

        return entries

@event('plugin.register')
def register_plugin():
    plugin.register(ImdbList, 'imdb_list', api_ver=2)

@@ -1045,16 +1045,21 @@
 ing 
+imdb 
 list: %25s
 ...'
@@ -1058,11 +1058,8 @@
 : %25s
-...
 ' %25 
@@ -2163,34 +2163,54 @@
 und in imdb list
-.'
+: %25s' %25 config%5B'list'%5D
 )%0A            re
@@ -2248,36 +2248,39 @@
     
-for 
 start
-_movie in xrange(1,
+ = 1%0A        while start %3C
  tot
@@ -2297,18 +2297,8 @@
 ount
- + 1, 250)
 :%0A  
@@ -2319,20 +2319,97 @@
 tart
-_movie %3E 250
+ == 1:%0A                trs = soup.find_all(attrs=%7B'data-item-id': True%7D)%0A            else
 :%0A  
@@ -2445,22 +2445,16 @@
  = start
-_movie
 %0A       
@@ -2815,17 +2815,20 @@
 =False)%0A
-%0A
+    
         
@@ -2873,32 +2873,33 @@
 tem-id': True%7D)%0A
+%0A
             for 
@@ -3544,16 +3544,54 @@
 entry)%0A%0A
+            start = len(entries) + 1%0A%0A
         

make imdb_list not assume the number of movies on a page is 250