import Vue from 'vue';
import { DASHBOARD_TYPES } from 'ee/security_dashboard/store/constants';
import { parseBoolean } from '~/lib/utils/common_utils';
import UnavailableState from './components/unavailable_state.vue';
import VulnerabilityReport from './components/vulnerability_report.vue';
import apolloProvider from './graphql/provider';
import createRouter from './router';
import createStore from './store';

export default (el, dashboardType) => {
  if (!el) {
    return null;
  }

  const {
    isUnavailable,
    dashboardDocumentation,
    emptyStateSvgPath,
    noVulnerabilitiesSvgPath,
    notEnabledScannersHelpPath,
    noPipelineRunScannersHelpPath,
    hasVulnerabilities,
    scanners,
    securityDashboardHelpPath,
    vulnerabilitiesExportEndpoint,
    projectFullPath,
    autoFixDocumentation,
    autoFixMrsPath,
    groupFullPath,
    instanceDashboardSettingsPath,
    pipelineCreatedAt,
    pipelineId,
    pipelinePath,
    pipelineSecurityBuildsFailedCount,
    pipelineSecurityBuildsFailedPath,
    hasJiraVulnerabilitiesIntegrationEnabled,
    securityConfigurationPath,
    surveyRequestSvgPath,
  } = el.dataset;

  if (isUnavailable) {
    return new Vue({
      el,
      render(createElement) {
        return createElement(UnavailableState, {
          props: {
            link: dashboardDocumentation,
            svgPath: emptyStateSvgPath,
          },
        });
      },
    });
  }

  const provide = {
    dashboardType,
    dashboardDocumentation,
    noVulnerabilitiesSvgPath,
    emptyStateSvgPath,
    notEnabledScannersHelpPath,
    noPipelineRunScannersHelpPath,
    instanceDashboardSettingsPath,
    securityDashboardHelpPath,
    securityConfigurationPath,
    surveyRequestSvgPath,
    vulnerabilitiesExportEndpoint,
    groupFullPath,
    projectFullPath,
    autoFixDocumentation,
    autoFixMrsPath,
    hasVulnerabilities: parseBoolean(hasVulnerabilities),
    scanners: scanners ? JSON.parse(scanners) : [],
    hasJiraVulnerabilitiesIntegrationEnabled: parseBoolean(
      hasJiraVulnerabilitiesIntegrationEnabled,
    ),
  };

  if (dashboardType === DASHBOARD_TYPES.PROJECT) {
    provide.pipeline = {
      createdAt: pipelineCreatedAt,
      id: pipelineId,
      path: pipelinePath,
      securityBuildsFailedCount: Number(pipelineSecurityBuildsFailedCount),
      securityBuildsFailedPath: pipelineSecurityBuildsFailedPath,
    };
  }

  const router = createRouter();
  const store = createStore({ dashboardType });

  return new Vue({
    el,
    store,
    router,
    apolloProvider,
    provide,
    render(createElement) {
      return createElement(VulnerabilityReport);
    },
  });
};
