<script>
import _ from 'underscore';
import { __ } from '~/locale';
import Project from '~/pages/projects/project';
import SmartInterval from '~/smart_interval';
import createFlash from '../flash';
import WidgetHeader from './components/mr_widget_header.vue';
import WidgetMergeHelp from './components/mr_widget_merge_help.vue';
import WidgetPipeline from './components/mr_widget_pipeline.vue';
import Deployment from './components/deployment.vue';
import WidgetRelatedLinks from './components/mr_widget_related_links.vue';
import MergedState from './components/states/mr_widget_merged.vue';
import ClosedState from './components/states/mr_widget_closed.vue';
import MergingState from './components/states/mr_widget_merging.vue';
import RebaseState from './components/states/mr_widget_rebase.vue';
import WorkInProgressState from './components/states/work_in_progress.vue';
import ArchivedState from './components/states/mr_widget_archived.vue';
import ConflictsState from './components/states/mr_widget_conflicts.vue';
import NothingToMergeState from './components/states/nothing_to_merge.vue';
import MissingBranchState from './components/states/mr_widget_missing_branch.vue';
import NotAllowedState from './components/states/mr_widget_not_allowed.vue';
import ReadyToMergeState from './components/states/ready_to_merge.vue';
import ShaMismatchState from './components/states/sha_mismatch.vue';
import UnresolvedDiscussionsState from './components/states/unresolved_discussions.vue';
import PipelineBlockedState from './components/states/mr_widget_pipeline_blocked.vue';
import PipelineFailedState from './components/states/pipeline_failed.vue';
import FailedToMerge from './components/states/mr_widget_failed_to_merge.vue';
import MergeWhenPipelineSucceedsState from './components/states/mr_widget_merge_when_pipeline_succeeds.vue';
import AutoMergeFailed from './components/states/mr_widget_auto_merge_failed.vue';
import CheckingState from './components/states/mr_widget_checking.vue';
import MRWidgetStore from './stores/ee_switch_mr_widget_store';
import MRWidgetService from './services/ee_switch_mr_widget_service';
import eventHub from './event_hub';
import stateMaps from './stores/ee_switch_state_maps';
import SquashBeforeMerge from './components/states/squash_before_merge.vue';
import notify from '~/lib/utils/notify';
import SourceBranchRemovalStatus from './components/source_branch_removal_status.vue';
import GroupedTestReportsApp from '../reports/components/grouped_test_reports_app.vue';
import { setFaviconOverlay } from '../lib/utils/common_utils';

export default {
  el: '#js-vue-mr-widget',
  name: 'MRWidget',
  components: {
    'mr-widget-header': WidgetHeader,
    'mr-widget-merge-help': WidgetMergeHelp,
    'mr-widget-pipeline': WidgetPipeline,
    Deployment,
    'mr-widget-related-links': WidgetRelatedLinks,
    'mr-widget-merged': MergedState,
    'mr-widget-closed': ClosedState,
    'mr-widget-merging': MergingState,
    'mr-widget-failed-to-merge': FailedToMerge,
    'mr-widget-wip': WorkInProgressState,
    'mr-widget-archived': ArchivedState,
    'mr-widget-conflicts': ConflictsState,
    'mr-widget-nothing-to-merge': NothingToMergeState,
    'mr-widget-not-allowed': NotAllowedState,
    'mr-widget-missing-branch': MissingBranchState,
    'mr-widget-ready-to-merge': ReadyToMergeState,
    'sha-mismatch': ShaMismatchState,
    'mr-widget-squash-before-merge': SquashBeforeMerge,
    'mr-widget-checking': CheckingState,
    'mr-widget-unresolved-discussions': UnresolvedDiscussionsState,
    'mr-widget-pipeline-blocked': PipelineBlockedState,
    'mr-widget-pipeline-failed': PipelineFailedState,
    'mr-widget-merge-when-pipeline-succeeds': MergeWhenPipelineSucceedsState,
    'mr-widget-auto-merge-failed': AutoMergeFailed,
    'mr-widget-rebase': RebaseState,
    SourceBranchRemovalStatus,
    GroupedTestReportsApp,
  },
  props: {
    mrData: {
      type: Object,
      required: false,
      default: null,
    },
  },
  data() {
    const store = new MRWidgetStore(this.mrData || window.gl.mrWidgetData);
    const service = this.createService(store);
    return {
      mr: store,
      state: store.state,
      service,
    };
  },
  computed: {
    componentName() {
      return stateMaps.stateToComponentMap[this.mr.state];
    },
    shouldRenderMergeHelp() {
      return stateMaps.statesToShowHelpWidget.indexOf(this.mr.state) > -1;
    },
    shouldRenderPipelines() {
      return this.mr.hasCI;
    },
    shouldRenderRelatedLinks() {
      return !!this.mr.relatedLinks && !this.mr.isNothingToMergeState;
    },
    shouldRenderSourceBranchRemovalStatus() {
      return (
        !this.mr.canRemoveSourceBranch &&
        this.mr.shouldRemoveSourceBranch &&
        (!this.mr.isNothingToMergeState && !this.mr.isMergedState)
      );
    },
    shouldRenderMergedPipeline() {
      return this.mr.state === 'merged' && !_.isEmpty(this.mr.mergePipeline);
    },
  },
  watch: {
    state(newVal, oldVal) {
      if (newVal !== oldVal && this.shouldRenderMergedPipeline) {
        // init polling
        this.initPostMergeDeploymentsPolling();
      }
    }
  },
  created() {
    this.initPolling();
    this.bindEventHubListeners();
    eventHub.$on('mr.discussion.updated', this.checkStatus);
  },
  mounted() {
    this.setFaviconHelper();
    this.initDeploymentsPolling();

    if (this.shouldRenderMergedPipeline) {
      this.initPostMergeDeploymentsPolling();
    }
  },
  beforeDestroy() {
    eventHub.$off('mr.discussion.updated', this.checkStatus);
    this.pollingInterval.destroy();
    this.deploymentsInterval.destroy();

    if (this.postMergeDeploymentsInterval) {
      this.postMergeDeploymentsInterval.destroy();
    }
  },
  methods: {
    createService(store) {
      const endpoints = {
        mergePath: store.mergePath,
        mergeCheckPath: store.mergeCheckPath,
        cancelAutoMergePath: store.cancelAutoMergePath,
        removeWIPPath: store.removeWIPPath,
        sourceBranchPath: store.sourceBranchPath,
        ciEnvironmentsStatusPath: store.ciEnvironmentsStatusPath,
        statusPath: store.statusPath,
        mergeActionsContentPath: store.mergeActionsContentPath,
        rebasePath: store.rebasePath,
      };
      return new MRWidgetService(endpoints);
    },
    checkStatus(cb) {
      return this.service
        .checkStatus()
        .then(res => res.data)
        .then(data => {
          this.handleNotification(data);
          this.mr.setData(data);
          this.setFaviconHelper();

          if (cb) {
            cb.call(null, data);
          }
        })
        .catch(() => createFlash(__('Something went wrong. Please try again.')));
    },
    setFaviconHelper() {
      if (this.mr.ciStatusFaviconPath) {
        return setFaviconOverlay(this.mr.ciStatusFaviconPath);
      }
      return Promise.resolve();
    },
    initPolling() {
      this.pollingInterval = new SmartInterval({
        callback: this.checkStatus,
        startingInterval: 10000,
        maxInterval: 30000,
        hiddenInterval: 120000,
        incrementByFactorOf: 5000,
      });
    },
    initDeploymentsPolling() {
      this.deploymentsInterval = this.deploymentsPoll(this.fetchPreMergeDeployments);
    },
    initPostMergeDeploymentsPolling() {
      this.postMergeDeploymentsInterval = this.deploymentsPoll(this.fetchPostMergeDeployments);
    },
    deploymentsPoll(callback) {
      return new SmartInterval({
        callback,
        startingInterval: 30000,
        maxInterval: 120000,
        hiddenInterval: 240000,
        incrementByFactorOf: 15000,
        immediateExecution: true,
      });
    },
    fetchDeployments(target) {
      return this.service.fetchDeployments(target);
    },
    fetchPreMergeDeployments() {
      return this.fetchDeployments()
        .then(({ data }) => {
          if (data.length) {
            this.mr.deployments = data;
          }
        })
        .catch(() => this.throwDeploymentsError());
    },
    fetchPostMergeDeployments(){
      return this.fetchDeployments('merge_commit')
        .then(({ data }) => {
          if (data.length) {
            this.mr.postMergeDeployments = data;
          }
        })
      .catch(() => this.throwDeploymentsError());
    },
    throwDeploymentsError() {
      createFlash(__('Something went wrong while fetching the environments for this merge request. Please try again.'));
    },
    fetchActionsContent() {
      this.service
        .fetchMergeActionsContent()
        .then(res => {
          if (res.data) {
            const el = document.createElement('div');
            el.innerHTML = res.data;
            document.body.appendChild(el);
            Project.initRefSwitcher();
          }
        })
        .catch(() => createFlash(__('Something went wrong. Please try again.')));
    },
    handleNotification(data) {
      if (data.ci_status === this.mr.ciStatus) return;
      if (!data.pipeline) return;

      const { label } = data.pipeline.details.status;
      const title = `Pipeline ${label}`;
      const message = `Pipeline ${label} for "${data.title}"`;

      notify.notifyMe(title, message, this.mr.gitlabLogo);
    },
    resumePolling() {
      this.pollingInterval.resume();
    },
    stopPolling() {
      this.pollingInterval.stopTimer();
    },
    bindEventHubListeners() {
      eventHub.$on('MRWidgetUpdateRequested', cb => {
        this.checkStatus(cb);
      });

      // `params` should be an Array contains a Boolean, like `[true]`
      // Passing parameter as Boolean didn't work.
      eventHub.$on('SetBranchRemoveFlag', params => {
        [this.mr.isRemovingSourceBranch] = params;
      });

      eventHub.$on('FailedToMerge', mergeError => {
        this.mr.state = 'failedToMerge';
        this.mr.mergeError = mergeError;
      });

      eventHub.$on('UpdateWidgetData', data => {
        this.mr.setData(data);
      });

      eventHub.$on('FetchActionsContent', () => {
        this.fetchActionsContent();
      });

      eventHub.$on('EnablePolling', () => {
        this.resumePolling();
      });

      eventHub.$on('DisablePolling', () => {
        this.stopPolling();
      });
    },
  },
};
</script>
<template>
  <div class="mr-state-widget prepend-top-default">
    <mr-widget-header
      :mr="mr"
    />
    <mr-widget-pipeline
      v-if="shouldRenderPipelines"
      :pipeline="mr.pipeline"
      :ci-status="mr.ciStatus"
      :has-ci="mr.hasCI"
      :source-branch="mr.sourceBranch"
      :source-branch-link="mr.sourceBranchLink"
      :troubleshooting-docs-path="mr.troubleshootingDocsPath"
    />
    <deployment
      v-for="deployment in mr.deployments"
      :key="`pre-merge-deploy-${deployment.id}`"
      class="js-pre-merge-deploy"
      :deployment="deployment"
    />
    <div class="mr-section-container">
      <grouped-test-reports-app
        v-if="mr.testResultsPath"
        class="js-reports-container"
        :endpoint="mr.testResultsPath"
      />

      <div class="mr-widget-section">
        <component
          :is="componentName"
          :mr="mr"
          :service="service"
        />

        <section
          v-if="mr.allowCollaboration"
          class="mr-info-list mr-links"
        >
          {{ s__("mrWidget|Allows commits from members who can merge to the target branch") }}
        </section>

        <mr-widget-related-links
          v-if="shouldRenderRelatedLinks"
          :state="mr.state"
          :related-links="mr.relatedLinks"
        />

        <source-branch-removal-status
          v-if="shouldRenderSourceBranchRemovalStatus"
        />
      </div>
      <div
        v-if="shouldRenderMergeHelp"
        class="mr-widget-footer"
      >
        <mr-widget-merge-help />
      </div>
    </div>

    <template v-if="shouldRenderMergedPipeline">
      <mr-widget-pipeline
        class="js-post-merge-pipeline prepend-top-default"
        :pipeline="mr.mergePipeline"
        :ci-status="mr.ciStatus"
        :has-ci="mr.hasCI"
        :source-branch="mr.targetBranch"
        :source-branch-link="mr.targetBranch"
        :troubleshooting-docs-path="mr.troubleshootingDocsPath"
      />
      <deployment
        v-for="postMergeDeployment in mr.postMergeDeployments"
        :key="`post-merge-deploy-${postMergeDeployment.id}`"
        :deployment="postMergeDeployment"
        class="js-post-deployment"
      />
    </template>
  </div>
</template>
