<template>
  <Dropdown class="x-admin-skin-dropdown" @command="handleCommand">
    <XIcon :icon="icon" :size="12" class="x-admin-icon-button"></XIcon>
    <DropdownMenu slot="dropdown">
      <DropdownItem v-for="item in items"
                    :key="item.theme"
                    :command="item"
                    class="x-admin-skin-dropdown__item"
                    :class="{'is-active':active === item.theme}">
        <span class="x-admin-skin-dropdown__icon" :class="item.theme"></span>
        <span class="x-admin-skin-dropdown__text">{{item.name}}</span>
      </DropdownItem>
    </DropdownMenu>
  </Dropdown>
</template>

<script>
import { Dropdown, DropdownMenu, DropdownItem } from 'element-ui';
import { XIcon } from '@newpearl/ui';
import { Skin } from '@newpearl/icons';

export default {
  inject: ['$admin'],
  components: {
    XIcon,
    Dropdown,
    DropdownMenu,
    DropdownItem
  },
  props: {
    items: Array,
    defaultTheme: String
  },
  data() {
    return {
      icon: Skin,
      active: null
    };
  },
  watch: {
    defaultTheme: {
      immediate: true,
      handler(v) {
        this.active = v;
      }
    },
    active: {
      immediate: true,
      handler(n, o) {
        this.setClass(n, o);
      }
    }
  },
  methods: {
    handleCommand(item) {
      this.active = item.theme;
      this.$admin.$emit('skin-change', item);
    },
    setClass(n, o) {
      const el = document.documentElement;
      if (!el) return;
      el.setAttribute('data-theme', n);
    }
  }
};
</script>
