'Create or configure a subreddit.
If `sr` is specified, the request will attempt to modify the specified
subreddit. If not, a subreddit with name `name` will be created.
This endpoint expects *all* values to be supplied on every request.  If
modifying a subset of options, it may be useful to get the current
settings from [/about/edit.json](#GET_r_{subreddit}_about_edit.json)
first.
For backwards compatibility, `description` is the sidebar text and
`public_description` is the publicly visible subreddit description.
Most of the parameters for this endpoint are identical to options
visible in the user interface and their meanings are best explained
there.
See also: [/about/edit.json](#GET_r_{subreddit}_about_edit.json).'

@require_oauth2_scope('modconfig')
@validatedForm(VUser(), VCaptcha(), VModhash(), VRatelimit(rate_user=True, rate_ip=True, prefix='create_reddit_'), sr=VByName('sr'), name=VAvailableSubredditName('name'), title=VLength('title', max_length=100), header_title=VLength('header-title', max_length=500), domain=VCnameDomain('domain'), submit_text=VMarkdownLength('submit_text', max_length=1024), public_description=VMarkdownLength('public_description', max_length=500), description=VMarkdownLength('description', max_length=5120), lang=VLang('lang'), over_18=VBoolean('over_18'), allow_top=VBoolean('allow_top'), show_media=VBoolean('show_media'), public_traffic=VBoolean('public_traffic'), collapse_deleted_comments=VBoolean('collapse_deleted_comments'), exclude_banned_modqueue=VBoolean('exclude_banned_modqueue'), spam_links=VOneOf('spam_links', ('low', 'high', 'all')), spam_selfposts=VOneOf('spam_selfposts', ('low', 'high', 'all')), spam_comments=VOneOf('spam_comments', ('low', 'high', 'all')), type=VOneOf('type', Subreddit.valid_types), link_type=VOneOf('link_type', ('any', 'link', 'self')), submit_link_label=VLength('submit_link_label', max_length=60), submit_text_label=VLength('submit_text_label', max_length=60), comment_score_hide_mins=VInt('comment_score_hide_mins', coerce=False, num_default=0, min=0, max=1440), wikimode=VOneOf('wikimode', ('disabled', 'modonly', 'anyone')), wiki_edit_karma=VInt('wiki_edit_karma', coerce=False, num_default=0, min=0), wiki_edit_age=VInt('wiki_edit_age', coerce=False, num_default=0, min=0), hide_ads=VBoolean('hide_ads'), suggested_comment_sort=VOneOf('suggested_comment_sort', CommentSortMenu._options, default=None))
@api_doc(api_section.subreddits)
def POST_site_admin(self, form, jquery, name, sr, **kw):

    def apply_wikid_field(sr, form, pagename, value, field):
        try:
            wikipage = wiki.WikiPage.get(sr, pagename)
        except tdb_cassandra.NotFound:
            wikipage = wiki.WikiPage.create(sr, pagename)
        wr = wikipage.revise(value, author=c.user._id36)
        setattr(sr, field, value)
        if wr:
            ModAction.create(sr, c.user, 'wikirevise', details=wiki.modactions.get(pagename))
    if feature.is_enabled('mobile_settings'):
        validator = VColor('key_color')
        value = request.params.get('key_color')
        kw['key_color'] = validator.run(value)
    if feature.is_enabled('related_subreddits'):
        validator = VSubredditList('related_subreddits', limit=20)
        value = request.params.get('related_subreddits')
        kw['related_subreddits'] = validator.run(value)
    if feature.is_enabled('autoexpand_media_previews'):
        validator = VBoolean('show_media_preview')
        value = request.params.get('show_media_preview')
        kw['show_media_preview'] = validator.run(value)
    form.parent().set_html('.status', '')
    redir = False
    keyword_fields = ['allow_top', 'collapse_deleted_comments', 'comment_score_hide_mins', 'description', 'domain', 'exclude_banned_modqueue', 'header_title', 'hide_ads', 'lang', 'link_type', 'name', 'over_18', 'public_description', 'public_traffic', 'show_media', 'show_media_preview', 'spam_comments', 'spam_links', 'spam_selfposts', 'submit_link_label', 'submit_text', 'submit_text_label', 'suggested_comment_sort', 'title', 'type', 'wiki_edit_age', 'wiki_edit_karma', 'wikimode']
    if feature.is_enabled('mobile_settings'):
        keyword_fields.append('key_color')
    if (sr and feature.is_enabled('related_subreddits')):
        keyword_fields.append('related_subreddits')
    kw = {k: v for (k, v) in kw.iteritems() if (k in keyword_fields)}
    public_description = kw.pop('public_description')
    description = kw.pop('description')
    submit_text = kw.pop('submit_text')
    def update_wiki_text(sr):
        error = False
        apply_wikid_field(sr, form, 'config/sidebar', description, 'description')
        apply_wikid_field(sr, form, 'config/submit_text', submit_text, 'submit_text')
        apply_wikid_field(sr, form, 'config/description', public_description, 'public_description')
    if ((not sr) and (not c.user.can_create_subreddit)):
        form.set_error(errors.CANT_CREATE_SR, '')
        c.errors.add(errors.CANT_CREATE_SR, field='')
    if ((not sr) and form.has_errors('captcha', errors.BAD_CAPTCHA)):
        return
    domain = kw['domain']
    cname_sr = (domain and Subreddit._by_domain(domain))
    if (cname_sr and ((not sr) or (sr != cname_sr))):
        c.errors.add(errors.USED_CNAME)
    can_set_archived = (c.user_is_admin or (sr and (sr.type == 'archived')))
    if ((kw['type'] == 'archived') and (not can_set_archived)):
        c.errors.add(errors.INVALID_OPTION, field='type')
    can_set_gold_restricted = (c.user_is_admin or (sr and (sr.type == 'gold_restricted')))
    if ((kw['type'] == 'gold_restricted') and (not can_set_gold_restricted)):
        c.errors.add(errors.INVALID_OPTION, field='type')
    can_set_gold_only = (c.user.gold or c.user.gold_charter or (sr and (sr.type == 'gold_only')))
    if ((kw['type'] == 'gold_only') and (not can_set_gold_only)):
        form.set_error(errors.GOLD_REQUIRED, 'type')
        c.errors.add(errors.GOLD_REQUIRED, field='type')
    can_set_hide_ads = (can_set_gold_only and (kw['type'] == 'gold_only'))
    if (kw['hide_ads'] and (not can_set_hide_ads)):
        form.set_error(errors.GOLD_ONLY_SR_REQUIRED, 'hide_ads')
        c.errors.add(errors.GOLD_ONLY_SR_REQUIRED, field='hide_ads')
    elif ((not can_set_hide_ads) and sr):
        kw['hide_ads'] = sr.hide_ads
    can_set_employees_only = c.user.employee
    if ((kw['type'] == 'employees_only') and (not can_set_employees_only)):
        c.errors.add(errors.INVALID_OPTION, field='type')
    if ((not sr) and form.has_errors('ratelimit', errors.RATELIMIT)):
        pass
    elif ((not sr) and form.has_errors('', errors.CANT_CREATE_SR)):
        pass
    elif (sr and (sr.type == 'employees_only') and (kw['type'] != sr.type) and (not c.user_is_admin)):
        form.set_error(errors.ADMIN_REQUIRED, 'type')
        c.errors.add(errors.ADMIN_REQUIRED, field='type')
    elif (sr and (sr.type != 'gold_only') and (kw['type'] == 'gold_only') and (not c.user_is_admin)):
        form.set_error(errors.CANT_CONVERT_TO_GOLD_ONLY, 'type')
        c.errors.add(errors.CANT_CONVERT_TO_GOLD_ONLY, field='type')
    elif form.has_errors('type', errors.GOLD_REQUIRED):
        pass
    elif ((not sr) and form.has_errors('name', errors.SUBREDDIT_EXISTS, errors.BAD_SR_NAME)):
        form.find('#example_name').hide()
    elif form.has_errors('title', errors.NO_TEXT, errors.TOO_LONG):
        form.find('#example_title').hide()
    elif form.has_errors('domain', errors.BAD_CNAME, errors.USED_CNAME):
        form.find('#example_domain').hide()
    elif (form.has_errors(('type', 'link_type', 'wikimode'), errors.INVALID_OPTION) or form.has_errors(('public_description', 'submit_text', 'description'), errors.TOO_LONG)):
        pass
    elif form.has_errors(('wiki_edit_karma', 'wiki_edit_age'), errors.BAD_NUMBER):
        pass
    elif form.has_errors('comment_score_hide_mins', errors.BAD_NUMBER):
        pass
    elif form.has_errors('related_subreddits', errors.SUBREDDIT_NOEXIST, errors.BAD_SR_NAME, errors.TOO_MANY_SUBREDDITS):
        pass
    elif form.has_errors('hide_ads', errors.GOLD_ONLY_SR_REQUIRED):
        pass
    elif (not sr):
        VNotInTimeout().run(action_name='createsubreddit', target=None)
        sr = Subreddit._new(name=name, author_id=c.user._id, ip=request.ip, **kw)
        update_wiki_text(sr)
        sr._commit()
        hooks.get_hook('subreddit.new').call(subreddit=sr)
        Subreddit.subscribe_defaults(c.user)
        sr.add_subscriber(c.user)
        sr.add_moderator(c.user)
        if (not sr.hide_contributors):
            sr.add_contributor(c.user)
        redir = (sr.path + 'about/edit/?created=true')
        if (not c.user_is_admin):
            VRatelimit.ratelimit(rate_user=True, rate_ip=True, prefix='create_reddit_')
        queries.new_subreddit(sr)
        sr.update_search_index()
    elif (sr.is_moderator_with_perms(c.user, 'config') or c.user_is_admin):
        VNotInTimeout().run(action_name='editsettings', target=sr)
        old_domain = sr.domain
        update_wiki_text(sr)
        if sr.quarantine:
            del kw['allow_top']
            del kw['show_media']
            del kw['show_media_preview']
        if (kw.get('over_18', False) and (not sr.over_18)):
            collections = []
            for collection in Collection.get_all():
                if ((sr.name in collection.sr_names) and (not collection.over_18)):
                    collections.append(collection.name)
            if collections:
                msg = '%s    now    NSFW,    in    collection(s)    %s'
                msg %= (sr.name, ',    '.join(collections))
                emailer.sales_email(msg)
        for (k, v) in kw.iteritems():
            if (getattr(sr, k, None) != v):
                ModAction.create(sr, c.user, action='editsettings', details=k)
            setattr(sr, k, v)
        sr._commit()
        if (sr.domain != old_domain):
            Subreddit._by_domain(old_domain, _update=True)
            Subreddit._by_domain(sr.domain, _update=True)
        sr.update_search_index()
        form.parent().set_text('.status', _('saved'))
    if form.has_error():
        return
    if redir:
        form.redirect(redir)
    else:
        jquery.refresh()
