# coding: utf-8
from __future__ import unicode_literals

import re
import urllib.request

from .common import InfoExtractor
from ..utils import determine_ext


class MegafilexIE(InfoExtractor):
    _VALID_URL = r'https?://(?:www\.)?megafilex\.com/video/[\w\+\%]+/(?P<id>[0-9]+).*'
    _TEST = {
        'url': 'http://www.megafilex.com/video/Japanese+Cutie+Sucking+And+Fucking+POV/207513/japanese-cutie-sucking-and-fucking-pov',
        'md5': '0480f1ef3932d901f0e0e719f188f19b',
        'info_dict': {
            'id': '207513',
            'ext': 'flv',
            'title': 'Japanese Cutie Sucking And Fucking POV',
        }
    }

    def _real_extract(self, url):
        mobj = re.match(self._VALID_URL, url)

        video_id = mobj.group('id')
        request=urllib.request.Request(url)
        request.add_header('Youtubedl-no-compression',"True")
        webpage = self._download_webpage(request, video_id)
        title = self._html_search_regex(r'<h1>([^<]*)</h1>', webpage, 'title')
        url2 = self._html_search_regex(
            r'config\s*=\s*(http[^\"]+)"', webpage, 'url2')
        uploader = self._html_search_regex(
            r'<a href="/user/([^"]+)">', webpage, 'uploader')
        print(uploader)
        request=urllib.request.Request(url2)
        request.add_header('Youtubedl-no-compression',"True")
        webpage = self._download_webpage(request, video_id)
        video_url = self._html_search_regex(
            r'<file>([^\<]+)</file>', webpage, 'video url')
        print(video_url)
        ext = determine_ext(video_url)
        return {
            'id': video_id,
            'url': video_url,
            'title': title,
            'ext': ext,
            'uploader': uploader
        }
