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

import re

from time import gmtime, mktime, strptime
from urlparse import urljoin

from module.plugins.Account import Account
from module.plugins.internal.SimpleHoster import parseHtmlForm, set_cookies


class XFSAccount(Account):
    __name__    = "XFSAccount"
    __type__    = "account"
    __version__ = "0.24"

    __description__ = """XFileSharing account plugin"""
    __license__     = "GPLv3"
    __authors__     = [("zoidberg", "zoidberg@mujmail.cz"),
                       ("Walter Purcaro", "vuolter@gmail.com")]


    """
    Following patterns should be defined by each hoster:

      PREMIUM_PATTERN: (optional) Checks if the account is premium
        example: PREMIUM_PATTERN = r'>Renew premium'
    """

    HOSTER_DOMAIN = None
    HOSTER_URL    = None

    COOKIES = [(HOSTER_DOMAIN, "lang", "english")]

    VALID_UNTIL_PATTERN = r'>Premium.[Aa]ccount expire:.*?(\d{1,2} [\w^_]+ \d{4})'

    TRAFFIC_LEFT_PATTERN = r'>Traffic available today:.*?<b>\s*(?P<S>[\d.,]+|[Uu]nlimited)\s*(?:(?P<U>[\w^_]+)\s*)?</b>'
    TRAFFIC_LEFT_UNIT    = "MB"  #: used only if no group <U> was found

    LOGIN_FAIL_PATTERN = r'>(Incorrect Login or Password|Error<)'


    def __init__(self, manager, accounts):  #@TODO: remove in 0.4.10
        self.init()
        return super(XFSAccount, self).__init__(manager, accounts)


    def init(self):
        # if not self.HOSTER_DOMAIN:
            # self.fail(_("Missing HOSTER_DOMAIN"))

        if not self.HOSTER_URL:
            self.HOSTER_URL = "http://www.%s/" % self.HOSTER_DOMAIN


    def loadAccountInfo(self, user, req):
        validuntil = None
        trafficleft = None
        premium = None

        html = req.load(self.HOSTER_URL, get={'op': "my_account"}, decode=True)

        if hasattr(self, "PREMIUM_PATTERN"):
            premium = True if re.search(self.PREMIUM_PATTERN, html) else False

        m = re.search(self.VALID_UNTIL_PATTERN, html)
        if m:
            expiredate = m.group(1).strip()
            self.logDebug("Expire date: " + expiredate)

            try:
                validuntil = mktime(strptime(expiredate, "%d %B %Y"))
            except Exception, e:
                self.logError(str(e))
            else:
                if validuntil > mktime(gmtime()):
                    premium = True
                else:
                    if premium is False:  #: registered account type (not premium)
                        validuntil = -1
                    premium = False

        m = re.search(self.TRAFFIC_LEFT_PATTERN, html)
        if m:
            try:
                traffic = m.groupdict()
                size = traffic['S']

                if "nlimited" in size:
                    trafficleft = -1
                    if premium is None:
                        premium = True
                else:
                    if 'U' in traffic:
                        unit = traffic['U']
                    elif isinstance(self.TRAFFIC_LEFT_UNIT, basestring):
                        unit = self.TRAFFIC_LEFT_UNIT
                    else:
                        unit = ""

                    trafficleft = self.parseTraffic(size + unit)

            except Exception, e:
                self.logError(str(e))

        return {'validuntil': validuntil, 'trafficleft': trafficleft, 'premium': premium or False}


    def login(self, user, data, req):
        if isinstance(self.COOKIES, list):
            set_cookies(req.cj, self.COOKIES)

        url = urljoin(self.HOSTER_URL, "login.html")
        html = req.load(url, decode=True)

        action, inputs = parseHtmlForm('name="FL"', html)
        if not inputs:
            inputs = {'op': "login",
                      'redirect': self.HOSTER_URL}

        inputs.update({'login': user,
                       'password': data['password']})

        html = req.load(self.HOSTER_URL, post=inputs, decode=True)

        if re.search(self.LOGIN_FAIL_PATTERN, html):
            self.wrongPassword()

@@ -330,17 +330,17 @@
 _ = %220.2
-4
+5
 %22%0A%0A    _
@@ -550,203 +550,8 @@
 %5D%0A%0A%0A
-    %22%22%22%0A    Following patterns should be defined by each hoster:%0A%0A      PREMIUM_PATTERN: (optional) Checks if the account is premium%0A        example: PREMIUM_PATTERN = r'%3ERenew premium'%0A    %22%22%22%0A%0A
     
@@ -649,16 +649,59 @@
 ish%22)%5D%0A%0A
+    PREMIUM_PATTERN = r'%5C(Premium only%5C)'%0A%0A
     VALI
@@ -1612,57 +1612,8 @@
 e)%0A%0A
-        if hasattr(self, %22PREMIUM_PATTERN%22):%0A    
     
@@ -2156,27 +2156,24 @@
         
-if 
 premium 
 is False
@@ -2168,135 +2168,95 @@
 ium 
-is
+=
  False
-:  #: registered account type (not premium)%0A                        validuntil = -1%0A                    premium = False
+%0A                    validuntil = None  #: registered account type (not premium)
 %0A%0A  
@@ -2515,23 +2515,26 @@
      if 
-premium
+validuntil
  is None
@@ -2555,38 +2555,39 @@
             
-premium = True
+validuntil = -1
 %0A           
@@ -3098,17 +3098,8 @@
 mium
- or False
 %7D%0A%0A%0A

Fix premium & validuntil detection