'Allow for changing the email notification settings where email is sent to a list of users
whenever the request state changes to one selected for notification.'

@web.expose
@web.require_login('edit    email    notification    settings')
def edit_email_settings(self, trans, cntrller, **kwd):

    params = util.Params(kwd)
    message = util.restore_text(params.get('message', ''))
    status = params.get('status', 'done')
    request_id = params.get('id', None)
    try:
        request = trans.sa_session.query(trans.model.Request).get(trans.security.decode_id(request_id))
    except:
        return invalid_id_redirect(trans, cntrller, request_id)
    email_address = CheckboxField.is_checked(params.get('email_address', ''))
    additional_email_addresses = params.get('additional_email_addresses', '')
    checked_sample_states = []
    for (index, sample_state) in enumerate(request.type.states):
        if CheckboxField.is_checked(params.get(('sample_state_%i' % sample_state.id), '')):
            checked_sample_states.append(sample_state.id)
    if additional_email_addresses:
        additional_email_addresses = additional_email_addresses.split('\r\n')
    if (email_address or additional_email_addresses):
        email_addresses = []
        if email_address:
            email_addresses.append(request.user.email)
        for email_address in additional_email_addresses:
            email_addresses.append(util.restore_text(email_address))
        err_msg = ''
        for email_address in email_addresses:
            err_msg += validate_email(trans, email_address, check_dup=False)
        if err_msg:
            status = 'error'
            message += err_msg
        else:
            request.notification = dict(email=email_addresses, sample_states=checked_sample_states, body='', subject='')
    else:
        request.notification = None
        if checked_sample_states:
            message = 'All    sample    states    have    been    unchecked    since    no    email    addresses    have    been    selected    or    entered.        '
    trans.sa_session.add(request)
    trans.sa_session.flush()
    trans.sa_session.refresh(request)
    message += 'The    changes    made    to    the    email    notification    settings    have    been    saved.'
    return trans.response.send_redirect(web.url_for(controller='requests_common', action='edit_basic_request_info', cntrller=cntrller, id=request_id, message=message, status=status))
