// @flow
import React from 'react';
import { expect } from 'chai';
import { mount } from 'enzyme';
import sinon from 'sinon';
import { spies } from '@test';

import { LibraryEditor as C } from '.';

import testLibs from '@test/test_libs.json';

describe('<LibraryEditor />', () => {
	let wrapper;

	afterEach(() => {
		if(wrapper && wrapper.unmount){
			wrapper.unmount();
		}
	});

	describe('accepts', () => {
		const libs = [
			{
				name: 'test/lib/1',
				contents: {
					language: 'python',
					uses: [],
				}
			}
		].concat(testLibs);

		libs.forEach(function(lib){
			const saveFunc = () => {};
			const updateFunc = () => {};
			it(`${ lib.name }`, () => {
				wrapper = mount(
					<C
						data={lib}
						libraries={libs}
						saveFunc={saveFunc}
						updateFunc={updateFunc}
					/>
				);

				expect(wrapper).to.have.props(
					['data', 'libraries', 'saveFunc', 'updateFunc']
				).deep.equal(
					[lib, libs, saveFunc, updateFunc]
				);
			});
		});
	});

	describe('creates', () => {
		it('user/anotherlib/1', () => {
			const libName = 'user/anotherlib/1';
			const saveFunc = sinon.spy();
			const updateFunc = sinon.spy();
			wrapper = mount(
				<C
					data={{name: libName, contents: { description: '', uses: {}, language: 'python' }}}
					libraries={testLibs.filter(l => l.name !== libName)}
					saveFunc={saveFunc}
					updateFunc={updateFunc}
				/>
			);

			expect(wrapper).to.have.props(
				['data', 'libraries', 'saveFunc']
			);

			expect(wrapper.props().data).to.have.property('name', libName);

			expect(wrapper.props().data.contents).to.deep.equal({
				'description': '',
				'uses': {},
				'language': 'python'
			});
		});

		it('user/thelib/1', () => {
			const libName = 'user/thelib/1';
			const saveFunc = sinon.spy();
			const data = {name: libName, contents: { description: '', uses: {}, language: 'python' }};
			const _updateFunc = (obj) => {
				wrapper.setProps && wrapper.setProps({ data: obj });
			};
			const updateFunc = sinon.spy(_updateFunc);
			wrapper = mount(
				<C
					data={data}
					libraries={testLibs.filter(l => l.name !== libName)}
					saveFunc={saveFunc}
					updateFunc={updateFunc}
				/>
			);

			expect(wrapper).to.have.props(
				['data', 'libraries', 'saveFunc', 'updateFunc']
			);

			let props = wrapper.props();
			expect(props.data).to.have.property('name', libName);

			wrapper.find('button#newLibrary').simulate('click');
			expect(updateFunc.callCount).to.equal(1);

			wrapper.find('#usedLibs CacheInput[type="text"]').prop('onChange')({ target: { value: 'lib'}});
			expect(updateFunc.callCount).to.equal(2);

			wrapper.find('#usedLibs select').simulate('change', { target: { value: 'user/anotherlib/1'}});
			expect(updateFunc.callCount).to.equal(3);

			props = wrapper.props();
			expect(props.data.contents).to.deep.equal({
				'description': '',
				'uses': {
					lib: 'user/anotherlib/1'
				},
				'language': 'python'
			});
		});
	});
});
