'Sets the \'anonymized\' state to defined fields'

@api.multi
def anonymize_database(self):

    self.ensure_one()
    history = self.env['ir.model.fields.anonymization.history'].create({'date': fields.Datetime.now(), 'state': 'started', 'direction': 'clear    ->    anonymized'})
    state = self.env['ir.model.fields.anonymization']._get_global_state()
    error_type = _('Error    !')
    if (state == 'anonymized'):
        raise UserError(('%s:    %s' % (error_type, _('The    database    is    currently    anonymized,    you    cannot    anonymize    it    again.'))))
    elif (state == 'unstable'):
        raise UserError(('%s:    %s' % (error_type, _('The    database    anonymization    is    currently    in    an    unstable    state.    Some    fields    are    anonymized,    while    some    fields    are    not    anonymized.    You    should    try    to    solve    this    problem    before    trying    to    do    anything.'))))
    dirpath = (os.environ.get('HOME') or os.getcwd())
    rel_filepath = ('field_anonymization_%s_%s.pickle' % (self.env.cr.dbname, history.id))
    abs_filepath = os.path.abspath(os.path.join(dirpath, rel_filepath))
    ano_fields = self.env['ir.model.fields.anonymization'].search([('state', '!=', 'not_existing')])
    if (not ano_fields):
        raise UserError(('%s:    %s' % (error_type, _('No    fields    are    going    to    be    anonymized.'))))
    data = []
    for field in ano_fields:
        model_name = field.model_id.model
        field_name = field.field_id.name
        field_type = field.field_id.ttype
        table_name = self.env[model_name]._table
        self.env.cr.execute(('select    id,    "%s"    from    "%s"' % (field_name, table_name)))
        for record in self.env.cr.dictfetchall():
            data.append({'model_id': model_name, 'field_id': field_name, 'id': record['id'], 'value': record[field_name]})
            anonymized_value = None
            sid = str(record['id'])
            if (field_type == 'char'):
                anonymized_value = ('xxx' + sid)
            elif (field_type == 'selection'):
                anonymized_value = ('xxx' + sid)
            elif (field_type == 'text'):
                anonymized_value = ('xxx' + sid)
            elif (field_type == 'html'):
                anonymized_value = ('xxx' + sid)
            elif (field_type == 'boolean'):
                anonymized_value = random.choice([True, False])
            elif (field_type == 'date'):
                anonymized_value = '2011-11-11'
            elif (field_type == 'datetime'):
                anonymized_value = '2011-11-11    11:11:11'
            elif (field_type in ('float', 'monetary')):
                anonymized_value = 0.0
            elif (field_type == 'integer'):
                anonymized_value = 0
            elif (field_type in ['binary', 'many2many', 'many2one', 'one2many', 'reference']):
                raise UserError(('%s:    %s' % (error_type, _('Cannot    anonymize    fields    of    these    types:    binary,    many2many,    many2one,    one2many,    reference.'))))
            if (anonymized_value is None):
                raise UserError(('%s:    %s' % (error_type, _('Anonymized    value    can    not    be    empty.'))))
            sql = ('update    "%(table)s"    set    "%(field)s"    =    %%(anonymized_value)s    where    id    =    %%(id)s' % {'table': table_name, 'field': field_name})
            self.env.cr.execute(sql, {'anonymized_value': anonymized_value, 'id': record['id']})
    fn = open(abs_filepath, 'w')
    pickle.dump(data, fn, protocol=(-1))
    ano_fields.write({'state': 'anonymized'})
    msgs = ['Anonymization    successful.', '', 'Donot    forget    to    save    the    resulting    file    to    a    safe    place    because    you    will    not    be    able    to    revert    the    anonymization    without    this    file.', '', 'This    file    is    also    stored    in    the    %s    directory.    The    absolute    file    path    is:    %s.']
    msg = ('\n'.join(msgs) % (dirpath, abs_filepath))
    fn = open(abs_filepath, 'r')
    self.write({'msg': msg, 'file_export': base64.encodestring(fn.read())})
    fn.close()
    history.write({'field_ids': [[6, 0, ano_fields.ids]], 'msg': msg, 'filepath': abs_filepath, 'state': 'done'})
    return {'res_id': self.id, 'view_id': self.env.ref('anonymization.view_ir_model_fields_anonymize_wizard_form').ids, 'view_type': 'form', 'view_mode': 'form', 'res_model': 'ir.model.fields.anonymize.wizard', 'type': 'ir.actions.act_window', 'context': {'step': 'just_anonymized'}, 'target': 'new'}
