#!/usr/bin/env python

import argparse
import os.path
import sqlite3
import sys
import time

import bs4
import requests


BABLA_HTTP_ENDPOINT = 'http://en.bab.la/%(dictionary)s/%(word)s'

DICTIONARY = 'english-polish'

SLEEP_SECONDS = 2


class Cli:

    delay = False
    delete = False
    words = []

    def __init__(self):
        self._parse_args()

    def _parse_args(self):
        parser = argparse.ArgumentParser(
            description='Helps you learn and memorize English by providing translations and excersises.'
        )
        parser.add_argument('words', metavar='N', type=str, nargs='*', help='list of words to operate on')
        parser.add_argument('--delay', dest='delay', action='store_true',
                            help='waits %d seconds before displaying the translation' % SLEEP_SECONDS)
        parser.add_argument('--delete', dest='delete', action='store_true',
                            help='deletes disappointing translation(s) passed as positional args')
        args = parser.parse_args()
        self.delay = args.delay
        self.delete = args.delete
        self.words = args.words

    def main(self):
        requests_wrapper = RequestsWrapper()
        sql_client = DictionaryModel()

        if self.words:
            if self.delete:
                for word in self.words:
                    sql_client.delete_translations(word)
            else:
                for word in self.words:
                    translations = sql_client.get_translations(word)
                    if not translations:
                        translations = requests_wrapper.get_translations(word)
                        sql_client.save_translations(word, translations)
                    print(', '.join(translations))

        else:
            random_word = sql_client.get_random_word()
            sys.stdout.write('%s: ' % random_word[0])
            sys.stdout.flush()
            if self.delay:
                time.sleep(SLEEP_SECONDS)
            sys.stdout.write(random_word[1])
            sys.stdout.write('\n')


class DictionaryModel:

    _connection = None
    _c = None

    def __init__(self, database=None):
        if database is None:
            database = os.path.join(os.path.dirname(__file__), 'dearbabla.db')
        self._connection = sqlite3.connect(database)
        self._c = self._connection.cursor()
        self._ensure_tables()

    def _ensure_tables(self):
        try:
            self._c.execute('CREATE TABLE words (dictionary TEXT, word TEXT, translations TEXT)')
        except sqlite3.OperationalError:
            pass  # table already exists

    def delete_translations(self, word):
        result = self._c.execute('DELETE FROM words WHERE dictionary=? AND word=?', (DICTIONARY, word, ))
        self._connection.commit()
        return result

    def get_random_word(self):
        result = self._c.execute('SELECT word, translations FROM words WHERE dictionary=? ORDER BY RANDOM()', (DICTIONARY, ))
        return result.fetchone()

    def get_translations(self, word):
        result = self._c.execute('SELECT translations FROM words WHERE dictionary=? AND word=?', (DICTIONARY, word, ))
        for row in result:
            return row[0].split(', ')

    def save_translations(self, word, translations):
        translations = ', '.join(translations)
        self._c.execute('INSERT INTO words VALUES (?, ?, ?)', (DICTIONARY, word, translations, ))
        self._connection.commit()


class RequestsWrapper:

    def _babla_get(self, *args, **kwargs):
        """
        Get babla request with prepared Chrome headers

        :return: response
        """
        headers = {
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
            'Accept-Language': 'en-GB,en;q=0.8,en-US;q=0.6,pl;q=0.4',
            'Referer': 'http://en.bab.la/',
            'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.115 Safari/537.36'
        }
        new_kwargs = {
            'headers': headers,
            'timeout': 2
        }
        new_kwargs.update(kwargs)
        return requests.get(*args, **new_kwargs)

    def get_translations(self, word):
        url = BABLA_HTTP_ENDPOINT % {'dictionary': DICTIONARY, 'word': word}
        response = self._babla_get(url)
        html_soup = bs4.BeautifulSoup(response.text)
        all_results = [r.text for r in html_soup.select('.result-block .result-right .result-link')]
        return all_results


def main():
    cli = Cli()
    cli.main()


if __name__ == '__main__':
    main()

@@ -277,24 +277,47 @@
 ete = False%0A
+    show_count = False%0A
     words = 
@@ -319,16 +319,16 @@
 ds = %5B%5D%0A
-
 %0A    def
@@ -663,16 +663,174 @@
 te on')%0A
+        parser.add_argument('--count', dest='show_count', action='store_true',%0A                            help='show how many words were already collected')%0A
         
@@ -1274,16 +1274,58 @@
 .delete%0A
+        self.show_count = args.show_count%0A
         
@@ -1974,16 +1974,202 @@
 ions))%0A%0A
+        elif self.show_count:%0A            database_count = sql_client.get_count()%0A            sys.stdout.write('Collected %25d words' %25 database_count)%0A            sys.stdout.write('%5Cn')%0A%0A
         
@@ -3203,24 +3203,24 @@
 on.commit()%0A
-
         retu
@@ -3230,16 +3230,141 @@
 result%0A%0A
+    def get_count(self):%0A        result = self._c.execute('SELECT COUNT(*) FROM words')%0A        return result.fetchone()%5B0%5D%0A%0A
     def 

Add --count option