import React from 'react';
import styled from 'styled-components';
import some from 'lodash/some';
import mockedIcon from 'ui/assets/images/mocked@2x.png';
import unmockedIcon from 'ui/assets/images/unmocked@2x.png';
import expandIcon from 'ui/assets/images/right@2x.png';
import Mock from 'ui/components/Mock';

const Icon = styled.img`
  height: 16px;
  user-select: none;
  margin-right: 5px;
  ${(props) => props.open ? 'transform: rotate(90deg);' : ''}
`;

const GroupHeader = styled.div`
  display: flex;
  align-items: center;
  padding: 4px;
  background-color: ${(props) => props.isSelected ? '#cbddf5' : 'white'};
  
  &:hover {
    cursor: ${(props) => props.isSelected ? 'default' : 'pointer'};
    background-color: #cbddf5;
  }
`;

const GroupMocks = styled.div`
  margin-left: 20px;
`;

export class Group extends React.Component {

  state = {
    isOpen: false
  };

  toggle = () => {
    this.setState({ isOpen: !this.state.isOpen });
  };

  componentWillReceiveProps(nextProps) {
    if (nextProps.searchTerm !== this.props.searchTerm) {
      this.checkMockMatch(nextProps.searchTerm);
    }
  }

  checkMockMatch(searchTerm) {
    const hasMatches = some(this.props.mocks, (mock) => mock.url.indexOf(searchTerm) > -1);

    if (hasMatches && !this.state.isOpen) {
      this.setState({ isOpen: true });
    }
  }

  render() {
    const { name, active, mocks, searchTerm, selectedMock, onSelectMock } = this.props;

    return (
      <div>
        <GroupHeader>
          <Icon src={ active ? mockedIcon : unmockedIcon } onClick={ this.props.toggleGroup }/>
          <Icon src={ expandIcon } onClick={ this.toggle } open={ this.state.isOpen }/>
          { name } {' '} ({ mocks.length })
        </GroupHeader>
        <GroupMocks>
          { this.state.isOpen && mocks.map((mock) => (
            <Mock
              key={ mock.id }
              id={ mock.id }
              name={ mock.name }
              active={ mock.isActive }
              method={ mock.method }
              url={ mock.url }
              searchTerm={ searchTerm }
              isSelected={ mock === selectedMock }
              toggleMock={ this.props.toggleMock(mock) }
              onClick={ onSelectMock(mock) }/>
          ))}
        </GroupMocks>
      </div>
    )
  }
}

Group.propTypes = {
  name: React.PropTypes.string,
  active: React.PropTypes.bool,
  mocks: React.PropTypes.array
};

export default Group;

@@ -870,17 +870,38 @@
 n: false
+,%0A    lastState: null
 %0A
-
   %7D;%0A%0A  
@@ -1119,16 +1119,24 @@
 archTerm
+ %7C%7C null
 );%0A    %7D
@@ -1322,32 +1322,40 @@
  this.setState(%7B
+%0A       
  isOpen: true %7D)
@@ -1351,16 +1351,217 @@
 en: true
+,%0A        lastState: this.state.isOpen%0A      %7D);%0A    %7D%0A%0A    if (!hasMatches && this.state.lastState !== null) %7B%0A      this.setState(%7B%0A        isOpen: this.state.lastState,%0A        lastState: null%0A     
  %7D);%0A   

Maintain last group state (open or not) when search no longer matches