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

@author: inso
'''

import os
import logging
import json
import tarfile
import shutil
import requests
import datetime

from PyQt5.QtCore import QObject, pyqtSignal

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)

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

        :param argv: The argv parameters of the call
        '''
        super().__init__()
        self.accounts = {}
        self.default_account = ""
        self.current_account = None
        self.monitor = None
        config.parse_arguments(argv)
        self.load()

    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

    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
        '''
        def progressing(value, maximum):
            self.loading_progressed.emit(value, maximum)

        if self.current_account is not None:
            self.monitor.stop_watching()
            self.save_cache(self.current_account)
        account.loading_progressed.connect(progressing)
        account.refresh_cache()
        self.monitor = Monitor(account)
        self.monitor.prepare_watching()
        self.current_account = account

    def load(self):
        '''
        Load a saved application state from the data file.
        Loads only jsonified objects but not their cache.

        If the standard application state file can't be found,
        no error is raised.
        '''
        self.load_persons()
        try:
            logging.debug("Loading data...")
            with open(config.parameters['data'], 'r') as json_data:
                data = json.load(json_data)
                if 'default_account' in data.keys():
                    self.default_account = data['default_account']
                for account_name in data['local_accounts']:
                    self.accounts[account_name] = None
        except FileNotFoundError:
            pass<commit_msg>Fixed a bug when creating first account<commit_after>'''
Created on 1 févr. 2014

@author: inso
'''

import os
import logging
import json
import tarfile
import shutil
import requests
import datetime

from PyQt5.QtCore import QObject, pyqtSignal

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)

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

        :param argv: The argv parameters of the call
        '''
        super().__init__()
        self.accounts = {}
        self.default_account = ""
        self.current_account = None
        self.monitor = None
        config.parse_arguments(argv)
        self.load()

    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

    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
        '''
        def progressing(value, maximum):
            self.loading_progressed.emit(value, maximum)

        if self.current_account is not None:
            if self.monitor:
                self.monitor.stop_watching()
            self.save_cache(self.current_account)
        account.loading_progressed.connect(progressing)
        account.refresh_cache()
        self.monitor = Monitor(account)
        self.monitor.prepare_watching()
        self.current_account = account

    def load(self):
        '''
        Load a saved application state from the data file.
        Loads only jsonified objects but not their cache.

        If the standard application state file can't be found,
        no error is raised.
        '''
        self.load_persons()
        try:
            logging.debug("Loading data...")
            with open(config.parameters['data'], 'r') as json_data:
                data = json.load(json_data)
                if 'default_account' in data.keys():
                    self.default_account = data['default_account']
                for account_name in data['local_accounts']:
                    self.accounts[account_name] = None
        except FileNotFoundError:
            pass
{'fraction_non_alphanumeric': 0.07684918347742556, 'fraction_numerical': 0.0016467682173734047, 'mean_word_length': 2.1118701964133217, 'pattern_counts': {'":': 0, '<': 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': '2726431', 'n_tokens_mistral': 1889, 'n_tokens_neox': 1815, 'n_words': 613}