<script>
import variables from '../../packages/theme-chalk/src/common/var.scss';

export default {
  name: 'breakpoint',
  data() {
    return {
      variables,
      breakpoint: {
        xsOnly: false,

        smOnly: false,
        smAndDown: false,
        smAndUp: false,

        mdOnly: false,
        mdAndDown: false,
        mdAndUp: false,

        lgOnly: false,
        lgAndDown: false,
        lgAndUp: false,

        xlOnly: false
      },
      mediaQueryObjects: []
    };
  },
  methods: {
    setupBreakpointListeners() {
      Object.keys(this.breakpoint).forEach(breakpointName => {
        if (process.env.NODE_ENV === 'development') {
          if (!(breakpointName in variables)) throw Error(`Breakpoint "${breakpointName}" not found in exported SCSS variables.`);
        }

        const media = window.matchMedia(variables[breakpointName]);
        this.breakpoint[breakpointName] = media.matches;
        const listener = e => {
          this.breakpoint[breakpointName] = e.matches;
        };
        try {
          media.addEventListener('change', listener);
        } catch (err) {
          media.addListener(listener); // for legacy browsers
        }

        this.mediaQueryObjects.push({ media, listener });
      });
    }
  },
  created() {
    this.setupBreakpointListeners();
  },
  beforeDestroy() {
    this.mediaQueryObjects.forEach(
      ({ media, listener }) => {
        try {
          media.removeEventListener('change', listener);
        } catch (err) {
          media.removeListener(listener);
        }
      }
    );
  }
};
</script>
