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

import re

from urlparse import urljoin

from module.plugins.Account import Account


class UlozTo(Account):
    __name__    = "UlozTo"
    __type__    = "account"
    __version__ = "0.09"

    __description__ = """Uloz.to account plugin"""
    __license__     = "GPLv3"
    __authors__     = [("zoidberg", "zoidberg@mujmail.cz"),
                       ("pulpe", None)]


    TRAFFIC_LEFT_PATTERN = r'<li class="menu-kredit"><a .*?title="[^"]*?GB = ([\d.]+) MB"'


    def loadAccountInfo(self, user, req):
        self.phpsessid = req.cj.getCookie("ULOSESSID")  #@NOTE: this cookie gets lost somehow after each request

        html = req.load("http://www.ulozto.net/", decode=True)

        req.cj.setCookie("ulozto.net", "ULOSESSID", self.phpsessid)

        m = re.search(self.TRAFFIC_LEFT_PATTERN, html)

        trafficleft = float(m.group(1).replace(' ', '').replace(',', '.')) * 1000 * 1.048 if m else 0
        premium     = True if trafficleft else False

        return {'validuntil': -1, 'trafficleft': trafficleft, 'premium': premium}


    def login(self, user, data, req):
        login_page = req.load('http://www.ulozto.net/?do=web-login', decode=True)
        action     = re.findall('<form action="(.+?)"', login_page)[1].replace('&amp;', '&')
        token      = re.search('_token_" value="(.+?)"', login_page).group(1)

        html = req.load(urljoin("http://www.ulozto.net/", action),
                        post={'_token_' : token,
                              'do'      : "loginForm-submit",
                              'login'   : u"Přihlásit",
                              'password': data['password'],
                              'username': user},
                        decode=True)

        if '<div class="flash error">' in html:
            self.wrongPassword()

@@ -207,10 +207,10 @@
  %220.
+1
 0
-9
 %22%0A%0A 
@@ -538,244 +538,61 @@
     
-self.phpsessid = req.cj.getCookie(%22ULOSESSID%22)  #@NOTE: this cookie gets lost somehow after each request%0A%0A        html = req.load(%22http://www.ulozto.net/%22, decode=True)%0A%0A        req.cj.setCookie(%22ulozto.net%22, %22ULOSESSID%22, self.phpsessid
+html = req.load(%22http://www.ulozto.net/%22, decode=True
 )%0A%0A 
@@ -1518,16 +1518,64 @@
 e': user
+,%0A                              'remember': %22on%22
 %7D,%0A     

Improve account login