<commit_before>'''
Created on 1 févr. 2014

@author: inso
'''

import os
import logging
import tarfile
import shutil
import json
import datetime
import i18n_rc

from PyQt5.QtCore import QObject, pyqtSignal, pyqtSlot, \
QUrl, QTranslator, QCoreApplication, QLocale
from PyQt5.QtNetwork import QNetworkAccessManager, QNetworkReply, QNetworkRequest

from . import config
from .account import Account
from . import person
from .watching.monitor import Monitor
from .. import __version__
from ..tools.exceptions import NameAlreadyExists, BadAccountFile


class Application(QObject):

    '''
    Managing core application datas :
    Accounts list and general configuration
    Saving and loading the application state
    '''

    loading_progressed = pyqtSignal(int, int)
    version_requested = pyqtSignal()

    def __init__(self, argv, qapp):
        '''
        Create a new "cutecoin" application

        :param argv: The argv parameters of the call
        '''
        super().__init__()
        self.accounts = {}
        self.current_account = None
        self.monitor = None
        self.available_version = __version__
        config.parse_arguments(argv)
        self._network_manager = QNetworkAccessManager()
        self._network_manager.finished.connect(self.read_available_version)
        self.get_last_version()
        self.preferences = {'account': "",
                            'lang': 'en_GB',
                            'ref': 'Units'
                            }

        self.load()

        translator = QTranslator(qapp)
        logging.debug("Loading translations")
        locale = self.preferences['lang']
        QLocale.setDefault(QLocale(locale))
        if translator.load(":/i18n/{0}".format(locale)):
            if QCoreApplication.installTranslator(translator):
                logging.debug("Loaded i18n/{0}".format(locale))
        else:
            logging.debug("Couldn't load translation")

    def get_account(self, name):
        '''
        Load an account then return it

        :param str name: The account name
        :return: The loaded account if it's a success, else return None
        '''
        self.load_account(name)
        if name in self.accounts.keys():
            return self.accounts[name]
        else:
            return None

    def create_account(self, name):
        '''
        Create a new account from its name

        :param str name: The account name
        :return: The new account
        :raise: NameAlreadyExists if the account name is already used locally
        '''
        for a in self.accounts:
            if a == name:
                raise NameAlreadyExists(a)

        account = Account.create(name)

        return account

    def add_account(self, account):
        self.accounts[account.name] = account

    def delete_account(self, account):
        '''
        Delete an account.
        Current account changes to None if it is deleted.
        '''
        self.accounts.pop(account.name)
        if self.current_account == account:
            self.current_account = None
        with open(config.parameters['data'], 'w') as outfile:
            json.dump(self.jsonify(), outfile, indent=4, sort_keys=True)

    def change_current_account(self, account):
        '''
        Change current account displayed and refresh its cache.

        :param account: The account object to display
        .. note:: Emits the application pyqtSignal loading_progressed
        during cache refresh<commit_msg>Fix bug in deleting account selected in preferences<commit_after>'''
Created on 1 févr. 2014

@author: inso
'''

import os
import logging
import tarfile
import shutil
import json
import datetime
import i18n_rc

from PyQt5.QtCore import QObject, pyqtSignal, pyqtSlot, \
QUrl, QTranslator, QCoreApplication, QLocale
from PyQt5.QtNetwork import QNetworkAccessManager, QNetworkReply, QNetworkRequest

from . import config
from .account import Account
from . import person
from .watching.monitor import Monitor
from .. import __version__
from ..tools.exceptions import NameAlreadyExists, BadAccountFile


class Application(QObject):

    '''
    Managing core application datas :
    Accounts list and general configuration
    Saving and loading the application state
    '''

    loading_progressed = pyqtSignal(int, int)
    version_requested = pyqtSignal()

    def __init__(self, argv, qapp):
        '''
        Create a new "cutecoin" application

        :param argv: The argv parameters of the call
        '''
        super().__init__()
        self.accounts = {}
        self.current_account = None
        self.monitor = None
        self.available_version = __version__
        config.parse_arguments(argv)
        self._network_manager = QNetworkAccessManager()
        self._network_manager.finished.connect(self.read_available_version)
        self.get_last_version()
        self.preferences = {'account': "",
                            'lang': 'en_GB',
                            'ref': 'Units'
                            }

        self.load()

        translator = QTranslator(qapp)
        logging.debug("Loading translations")
        locale = self.preferences['lang']
        QLocale.setDefault(QLocale(locale))
        if translator.load(":/i18n/{0}".format(locale)):
            if QCoreApplication.installTranslator(translator):
                logging.debug("Loaded i18n/{0}".format(locale))
        else:
            logging.debug("Couldn't load translation")

    def get_account(self, name):
        '''
        Load an account then return it

        :param str name: The account name
        :return: The loaded account if it's a success, else return None
        '''
        self.load_account(name)
        if name in self.accounts.keys():
            return self.accounts[name]
        else:
            return None

    def create_account(self, name):
        '''
        Create a new account from its name

        :param str name: The account name
        :return: The new account
        :raise: NameAlreadyExists if the account name is already used locally
        '''
        for a in self.accounts:
            if a == name:
                raise NameAlreadyExists(a)

        account = Account.create(name)

        return account

    def add_account(self, account):
        self.accounts[account.name] = account

    def delete_account(self, account):
        '''
        Delete an account.
        Current account changes to None if it is deleted.
        '''
        self.accounts.pop(account.name)
        if self.current_account == account:
            self.current_account = None
        with open(config.parameters['data'], 'w') as outfile:
            json.dump(self.jsonify(), outfile, indent=4, sort_keys=True)
        if self.preferences['account'] == account.name:
            self.preferences['account'] = ""
            self.save_preferences(self.preferences)

    def change_current_account(self, account):
        '''
        Change current account displayed and refresh its cache.

        :param account: The account object to display
        .. note:: Emits the application pyqtSignal loading_progressed
        during cache refresh
{'fraction_non_alphanumeric': 0.08605588766856666, 'fraction_numerical': 0.0044487696371472265, 'mean_word_length': 2.3259361997226073, 'pattern_counts': {'":': 2, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2193932', 'n_tokens_mistral': 1929, 'n_tokens_neox': 1863, 'n_words': 565}