#! /usr/local/bin/python
import argparse
import os

import requests


class LeetCode:
    LOGIN_URI = 'https://leetcode.com/accounts/login/'
    HEADERS = {
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',  # NOQA E501
        'Accept-Encoding': 'gzip, deflate, sdch',
        'Accept-Language': 'en-US,en;q=0.8,zh-CN;q=0.6,zh;q=0.4,zh-TW;q=0.2',
        'Connection': 'keep-alive',
        'Host': 'leetcode.com',
        'Referer': 'https://leetcode.com/accounts/login/',
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:56.0) Gecko/20100101 Firefox/56.0', # NOQA E501
        'Content-Type': 'application/x-www-form-urlencoded',
    }

    def __init__(self, username, password):
        self.username = username
        self.password = password
        self.session = requests.Session()
        self.login()

    def _get_csrfmiddlewaretoken(self):
        resp = self.session.get(self.LOGIN_URI, headers=self.HEADERS)
        # <input type='hidden' name='csrfmiddlewaretoken' value='B5yVhk7grKZU4rt3hNxGZ9NUB67lmIW0RuAg75Vx9f3WA8grGIV4qI2eFbmlK6Dq' />  # NOQA E501
        return resp.text.split('csrfmiddlewaretoken')[1].split("'")[2]

    def login(self):
        data = {
            'csrfmiddlewaretoken': self._get_csrfmiddlewaretoken(),
            'login': self.username,
            'password': self.password,
        }
        resp = self.session.post(
            self.LOGIN_URI, data=data, headers=self.HEADERS)
        if resp.status_code != 200:
            print("Login failed.", resp.status_code)
            os._exit(1)

    def all(self):
        url = 'https://leetcode.com/api/progress/all/'
        resp = self.session.get(url)
        if resp.status_code != 200:
            print("request failed:", resp.status_code)
            os._exit(1)
        data = resp.json()
        print('{unsolved} Todo | {solvedTotal}/{questionTotal} Solved'
              ' | {attempted} Attempted'.format(**data))
        print('Easy {Easy} Medium {Medium} Hard {Hard}'.format(
            **data['solvedPerDifficulty']))

    def analysis(self, allstatistics):
        if allstatistics:
            self.all()


parser = argparse.ArgumentParser(
    description='Analysis leetcode problems progress.')
parser.add_argument('-u', '--username', type=str, required=True,
                    help='Username for login.')
parser.add_argument('-p', '--password', type=str, required=True,
                    help='Password to use when connecting to leetcode.')
parser.add_argument('-a', '--allstatistics', action='store_true',
                    help='Show all statistical information.')


if __name__ == '__main__':
    args = parser.parse_args()
    leetcode = LeetCode(username=args.username, password=args.password)
    leetcode.analysis(allstatistics=args.allstatistics)

@@ -43,16 +43,30 @@
 mport os
+%0Aimport pprint
 %0A%0Aimport
@@ -76,16 +76,45 @@
 quests%0A%0A
+pp = pprint.PrettyPrinter()%0A%0A
 %0Aclass L
@@ -786,16 +786,28 @@
 password
+, difficulty
 ):%0A     
@@ -867,16 +867,53 @@
 assword%0A
+        self.difficulty = difficulty%0A
         
@@ -2187,16 +2187,726 @@
 ty'%5D))%0A%0A
+    def get_unsolved_problem(self):%0A        # get a problem by difficulty filter%0A        level_maps = %7B%0A            %22easy%22: 1,%0A            %22medium%22: 2,%0A            %22hard%22: 3,%0A        %7D%0A%0A        url = 'https://leetcode.com/api/problems/all/'%0A        data = self.session.get(url).json()%0A%0A        pairs = sorted(data%5B'stat_status_pairs'%5D,%0A                       key=lambda x: x%5B'stat'%5D%5B'question_id'%5D)%0A        pairs = filter(lambda x: x%5B'paid_only'%5D is False, pairs)%0A        pairs = filter(lambda x: x%5B'status'%5D is None, pairs)%0A        if self.difficulty:%0A            level = level_maps%5Bself.difficulty%5D%0A            pairs = filter(lambda x: x%5B'difficulty'%5D%5B'level'%5D == level, pairs)%0A%0A        pp.pprint(pairs%5B0%5D)%0A%0A
     def 
@@ -2933,16 +2933,23 @@
 atistics
+, query
 ):%0A     
@@ -2992,16 +2992,74 @@
 f.all()%0A
+        if query:%0A            self.get_unsolved_problem()%0A
 %0A%0Aparser
@@ -3419,116 +3419,407 @@
 t('-
-a', '--allstatistics', action='store_true',%0A                    help='Show all statistical information.')%0A
+d', '--difficulty', type=str,%0A                    choices=('easy', 'medium', 'hard'),%0A                    help='Difficulty of problems.')%0A%0Aparser.add_argument('-a', '--allstatistics', action='store_true',%0A                    help='Show all statistical information.')%0Aparser.add_argument('-query', '--query', action='store_true',%0A                    help='Query one unsolved problem order by id.')
 %0A%0A
+%0A
 if _
@@ -3942,16 +3942,68 @@
 password
+,%0A                        difficulty=args.difficulty
 )%0A    le
@@ -4050,10 +4050,28 @@
 atistics
+, query=args.query
 )%0A

add query cmd: query one unsolved problem order by id