import hashlib
import requests


from .base import NanoBase


class User(NanoBase):
    """
    A NanoBase object for representing NaNoWriMo participants.
    """
    # Endpoint URLs for user objects
    _primary_url = 'http://nanowrimo.org/wordcount_api/wc/{name}'
    _history_url = 'http://nanowrimo.org/wordcount_api/wchistory/{name}'

    __secret_key = None

    def __init__(self, name, secret_key=None, **kwargs):
        super().__init__(name, **kwargs)

        self.secret_key = secret_key

    @property
    def id(self):
        """The User's id.

        This property corresponds to `uid` in the API.

        :rtype: string
        """
        return self._fetch_element('uid')

    @property
    def name(self):
        """The User's username.

        This property corresponds to `uname` in the API.

        :rtype: string
        """
        return self._fetch_element('uname')

    @property
    def wordcount(self):
        """The User's current word count.

        This property corresponds to `user_wordcount` in the API.

        :rtype: int
        """
        return int(self._fetch_element('user_wordcount'))

    @wordcount.setter
    def wordcount(self, val):
        """Update the User's current word count.

        This uses the NaNoWriMo WriteAPI and the User's `secret_key` to update
        the wordcount on the NaNoWriMo website.

        :param int val: The User's new word count
        """
        if self.secret_key is None:
            raise ValueError('secret_key must be set before wordcount can be')

        if val != self.wordcount:
            val = int(val)
            name = self.name
            key = self.__secret_key
            h = hashlib.sha1(key.encode() + name.encode() + str(val).encode()).hexdigest()

            data = {
                    'hash':h,
                    'name':name,
                    'wordcount':val,
                    }

            r = requests.put('https://nanowrimo.org/api/wordcount', data=data)

            if not r.ok:
                r.raise_for_status()

    @property
    def winner(self):
        """The User's "winner" status.

        This property corresponds to `winner` in the API.

        :rtype: bool
        """
        return self._fetch_element('winner') == 'true'

    @property
    def secret_key(self):
        """The User's WriteAPI key.

        This is not actually returned; if the key has been set you will get a
        string of '*' characters. Returns None if no key has been set.

        :rtype: string
        """
        if self.__secret_key is not None:
            return '*' * len(self.__secret_key)

        return None

    @secret_key.setter
    def secret_key(self, val):
        """Set the User's WriteAPI key.

        :param string val: The User's WriteAPI secret key
        """
        self.__secret_key = val


@@ -1663,24 +1663,25 @@
 _secret_key%0A
+%0A
             
@@ -1701,39 +1701,102 @@
 ha1(
-key.encode() + name.encode() + 
+)%0A            h.update(key.encode())%0A            h.update(name.encode())%0A            h.update(
 str(
@@ -1813,20 +1813,8 @@
 e())
-.hexdigest()
 %0A%0A  
@@ -1860,16 +1860,28 @@
 'hash':h
+.hexdigest()
 ,%0A      

Use sequence of update() calls