1#!/usr/bin/python
2# -*- coding: utf-8 -*-
3from __future__ import print_function
4
5from .base.weboobmc2 import Weboobmc
6from weboob.capabilities.video import BaseVideo, CapVideo
7from weboob.capabilities.collection import CapCollection, Collection
8
9
10class Videoobmc(Weboobmc):
11    def __init__(self, count=10, nsfw=False):
12        Weboobmc.__init__(self, count=count)
13        self.backends = self.weboob.load_backends(CapVideo)
14        self.nsfw = nsfw
15
16    def search(self, pattern, backend=''):
17        kwargs = {'pattern': pattern,
18                  'nsfw': self.nsfw,
19                  'backends': backend}
20
21        fields = ['id', 'title', 'date', 'description', 'author', 'duration', 'thumbnail', 'url']
22        try:
23            for video in self.weboob.do(self._do_complete, self.count, fields, 'search_videos', **kwargs):
24                yield video
25        except Exception as e:
26            print(e)
27
28    def get_video(self, video, _backend):
29        backend = self.weboob.get_backend(_backend)
30        fields = ['id', 'title', 'date', 'description', 'author', 'duration', 'thumbnail', 'url']
31        return backend.fillobj(video, fields)
32
33    def ls(self, backend, path=''):
34        kwargs = {'split_path':  path.split('/') if path else [],
35                  'caps': CapCollection,
36                  'objs': (BaseVideo, ),
37                  'backends': backend}
38        fields = []  # ['id', 'title', 'date', 'description', 'author', 'duration', 'thumbnail', 'url']
39        result = self.weboob.do(self._do_complete, self.count, fields, 'iter_resources', **kwargs)
40        return self.separate_collections_and_videos(result)
41
42    def separate_collections_and_videos(self, objs):
43        videos = []
44        categories = []
45        for obj in objs:
46            if isinstance(obj, Collection):
47                categories.append(obj)
48            else:
49                videos.append(obj)
50        return categories, videos
51
52    def download(self, _id, dest, backend):
53        for _video in self.weboob.do('get_video', _id, backends=backend):
54            self.download_obj(_video, dest)
55