import { extend, override } from 'flarum/extend';
import PermissionGrid from 'flarum/components/PermissionGrid';
import PermissionDropdown from 'flarum/components/PermissionDropdown';
import Dropdown from 'flarum/components/Dropdown';
import Button from 'flarum/components/Button';

import tagLabel from '../common/helpers/tagLabel';
import tagIcon from '../common/helpers/tagIcon';
import sortTags from '../common/utils/sortTags';

export default function() {
  override(app, 'getRequiredPermissions', (original, permission) => {
    const tagPrefix = permission.match(/^tag\d+\./);

    if (tagPrefix) {
      const globalPermission = permission.substr(tagPrefix[0].length);

      const required = original(globalPermission);

      return required.map(required => tagPrefix[0] + required);
    }

    return original(permission);
  });

  extend(PermissionGrid.prototype, 'scopeItems', items => {
    sortTags(app.store.all('tags'))
      .filter(tag => tag.isRestricted())
      .forEach(tag => items.add('tag' + tag.id(), {
        label: tagLabel(tag),
        onremove: () => tag.save({isRestricted: false}),
        render: item => {
          if (item.permission === 'viewForum'
            || item.permission === 'startDiscussion'
            || (item.permission && item.permission.indexOf('discussion.') === 0 && item.tagScoped !== false)
            || item.tagScoped) {
            return PermissionDropdown.component({
              permission: 'tag' + tag.id() + '.' + item.permission,
              allowGuest: item.allowGuest
            });
          }

          return '';
        }
      }));
  });

  extend(PermissionGrid.prototype, 'scopeControlItems', items => {
    const tags = sortTags(app.store.all('tags').filter(tag => !tag.isRestricted()));

    if (tags.length) {
      items.add('tag', <Dropdown className='Dropdown--restrictByTag' buttonClassName='Button Button--text' label={app.translator.trans('flarum-tags.admin.permissions.restrict_by_tag_heading')} icon='fas fa-plus' caretIcon={null}>
        {tags.map(tag => <Button icon={true} onclick={() => tag.save({ isRestricted: true })}>
          {[tagIcon(tag, { className: 'Button-icon' }), ' ', tag.name()]}
        </Button>)}
      </Dropdown>);
    }
  });
}

@@ -274,16 +274,83 @@
 Button';
+%0Aimport LoadingIndicator from 'flarum/components/LoadingIndicator';
 %0A%0Aimport
@@ -521,16 +521,443 @@
 ion() %7B%0A
+  extend(PermissionGrid.prototype, 'oninit', function () %7B%0A    this.loading = true;%0A  %7D)%0A%0A  extend(PermissionGrid.prototype, 'oncreate', function () %7B%0A    app.store.find('tags').then(() =%3E %7B%0A      this.loading = false;%0A%0A      m.redraw();%0A    %7D);%0A  %7D);%0A%0A  override(PermissionGrid.prototype, 'view', function (original, vnode) %7B%0A    if (this.loading) %7B%0A      return %3CLoadingIndicator /%3E;%0A    %7D%0A%0A    return original(vnode);%0A  %7D)%0A%0A
   overri

Load all tags in permission grid