import PropTypes from 'prop-types';
import React from 'react';

import {mount} from 'enzyme';
import ProjectKeys from 'app/views/settings/project/projectKeys';

describe('ProjectKeys', function() {
  let org, project, wrapper;
  let deleteMock;
  let projectKeys;

  beforeEach(function() {
    org = TestStubs.Organization();
    project = TestStubs.Project();
    projectKeys = TestStubs.ProjectKeys();

    MockApiClient.clearMockResponses();
    MockApiClient.addMockResponse({
      url: `/projects/${org.slug}/${project.slug}/keys/`,
      method: 'GET',
      body: projectKeys,
    });
    deleteMock = MockApiClient.addMockResponse({
      url: `/projects/${org.slug}/${project.slug}/keys/${projectKeys[0].id}/`,
      method: 'DELETE',
    });
    let routerContext = TestStubs.routerContext();

    wrapper = mount(
      <ProjectKeys routes={[]} params={{orgId: org.slug, projectId: project.slug}} />,
      {
        ...routerContext,
        context: {
          ...routerContext.context,
          project: TestStubs.Project(),
        },
        childContextTypes: {
          ...routerContext.childContextTypes,
          project: PropTypes.object,
        },
      }
    );
  });

  it('renders empty', function() {
    MockApiClient.clearMockResponses();
    MockApiClient.addMockResponse({
      url: `/projects/${org.slug}/${project.slug}/keys/`,
      method: 'GET',
      body: [],
    });

    wrapper = mount(
      <ProjectKeys routes={[]} params={{orgId: org.slug, projectId: project.slug}} />,
      TestStubs.routerContext()
    );

    expect(wrapper.find('EmptyMessage')).toHaveLength(1);
  });

  it('has clippable box', function() {
    expect(wrapper.find('.clip-fade .btn')).toHaveLength(1);
    wrapper.find('.clip-fade .btn').simulate('click');
    expect(wrapper.find('.clip-fade .btn')).toHaveLength(0);
  });

  it('deletes key', function() {
    wrapper
      .find('PanelHeader Button')
      .last()
      .simulate('click');

    wrapper.find('ModalDialog Button[priority="danger"]').simulate('click');

    wrapper.update();

    expect(deleteMock).toHaveBeenCalled();
  });

  it('disable and enables key', function() {
    let enableMock = MockApiClient.addMockResponse({
      url: `/projects/${org.slug}/${project.slug}/keys/${projectKeys[0].id}/`,
      method: 'PUT',
    });

    wrapper
      .find('PanelHeader Button')
      .at(1)
      .simulate('click');

    expect(enableMock).toHaveBeenCalledWith(
      expect.anything(),
      expect.objectContaining({
        data: {isActive: false},
      })
    );

    wrapper
      .find('PanelHeader Button')
      .at(1)
      .simulate('click');

    expect(enableMock).toHaveBeenCalledWith(
      expect.anything(),
      expect.objectContaining({
        data: {isActive: true},
      })
    );
  });
});
