import React, { Component } from 'react';
import { List } from 'immutable';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { createSelector } from 'reselect';

import { authActions, getAuth } from 'src/auth';
import { getNotification, notificationActions } from 'src/notification';
import { getTaskFilter, getVisibleTasks, tasksActions, taskFilters } from 'src/tasks';
import { commentsActions } from 'src/comments';
import Notification from '../../components/notification';
import TaskFilters from '../../components/task-filters';
import TaskList from '../../components/task-list';
import TaskView from '../../components/task-view/task-view';
import Button from '../../components/button';
import classNames from 'classnames';

import './tasks-page.css';

export class TasksPage extends Component {
  constructor() {
    super(...arguments);
    this.createNewTask = this.createNewTask.bind(this);
    this.isAdmin = this.isAdmin.bind(this);
    this.assignTaskToSignedUser = this.assignTaskToSignedUser.bind(this);
    this.selectTaskAndSetComments = this.selectTaskAndSetComments.bind(this);
    
    this.state = {selectedTask: null};
  }

  static propTypes = {
    createTask: PropTypes.func.isRequired,
    dismissNotification: PropTypes.func.isRequired,
    filterTasks: PropTypes.func.isRequired,
    filterType: PropTypes.object.isRequired,
    loadTasks: PropTypes.func.isRequired,
    location: PropTypes.object.isRequired,
    notification: PropTypes.object.isRequired,
    removeTask: PropTypes.func.isRequired,
    assignTask: PropTypes.func.isRequired,
    tasks: PropTypes.instanceOf(List).isRequired,
    undeleteTask: PropTypes.func.isRequired,
    unloadTasks: PropTypes.func.isRequired,
    unloadComments: PropTypes.func.isRequired,
    updateTask: PropTypes.func.isRequired,
    auth: PropTypes.object.isRequired
  };

  static contextTypes = {
    tasks: PropTypes.object.isRequired,
  }

  componentWillMount() {
    this.props.loadTasks();
    this.props.filterTasks(
      this.getFilterParam(this.props.location.search)
    );
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.location.search !== this.props.location.search) {
      this.props.filterTasks(
        this.getFilterParam(nextProps.location.search)
      );  
    }

    // if url has a task id - select it
    if (this.props.match != null) {
      if (this.state.selectedTask == null || this.state.selectedTask.get("id") != nextProps.match.params.id) {
        const tid = nextProps.match.params.id;

        this.setState({
          selectedTask: this.props.tasks.find((task)=>( task.get('id') == tid ))
        })
      }
    } else {
      this.selectTaskAndSetComments();
    }
  }

  componentWillUnmount() {
    this.props.unloadTasks();
  }

  getFilterParam(search) {
    const params = new URLSearchParams(search);
    let filterParams = {};
    filterParams.name = params.get('filter');
    filterParams.text = params.get('text');
    return filterParams;
  }

  renderNotification() {
    const { notification } = this.props;
    return (
      <Notification
        action={this.props.undeleteTask}
        actionLabel={notification.actionLabel}
        dismiss={this.props.dismissNotification}
        display={notification.display}
        message={notification.message}
      />
    );
  }

  createNewTask() {
    let creator = {
      id: this.props.auth.id,
      name: this.props.auth.name,
      email: this.props.auth.email,
      photoURL: this.props.auth.photoURL,
    }
    
    this.props.createTask({creator , title: `משימה חדשה של ${creator.name}`, created: new Date()});
    // TODO Select the new created task
  }

  isAdmin() {
    return false; //TODO
  }

  assignTaskToSignedUser(task) {
    this.props.assignTask(task, this.props.auth);
  }

  // TODO - Better handle it on the redux level and on each
  // call to select task - load the correct comments
  selectTaskAndSetComments(task) {
    this.props.history.push(`/task/${task.get("id")}`);
  }

  renderTaskView() {
    if (this.state.selectedTask == null) return null; 
    
    return (
      <TaskView 
        createTask={this.props.createTask}
        removeTask={this.props.removeTask}
        updateTask={this.props.updateTask}
        selectTask={this.selectTaskAndSetComments}
        selectedTask={this.state.selectedTask.toJS()}
        isAdmin={false}
        assignTask={this.assignTaskToSignedUser}
        unloadComments={this.props.unloadComments}
        createComment={this.props.createComment}
      />)
  }

  render() {
    return (
      <div>
          <div className="g-col">
            <TaskFilters filter={this.props.filterType} />
            <Button
              className="button button-small add-task-button"
              onClick={ this.createNewTask }>
              הוסף משימה
            </Button>
          </div>
      
        <div className="g-row">
          <div className="g-col-60 g-col-xs-100">
            { this.renderTaskView() }
          </div>
          <div className="g-col-40 g-col-xs-100">
            <TaskList
              tasks={this.props.tasks}
              selectTask={this.selectTaskAndSetComments}
            />
          </div>

          {this.props.notification.display ? this.renderNotification() : null}
        </div>
      </div>
    );
  }
}


//=====================================
//  CONNECT
//-------------------------------------

const mapStateToProps = createSelector(
  getNotification,
  getTaskFilter,
  getVisibleTasks,
  getAuth,
  (notification, filterType, tasks, auth, getVisibleTasks) => ({
    notification,
    filterType,
    tasks,
    auth
  })
);

const mapDispatchToProps = Object.assign(
  {},
  tasksActions,
  commentsActions,
  notificationActions
);

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(TasksPage);
@@ -2124,24 +2124,70 @@
 extProps) %7B%0A
+    console.log(%22tasks page got new props%22);%0A%0A
     if (next
@@ -2425,121 +2425,8 @@
 ) %7B%0A
-      if (this.state.selectedTask == null %7C%7C this.state.selectedTask.get(%22id%22) != nextProps.match.params.id) %7B%0A  
     
@@ -2469,26 +2469,24 @@
 .id;%0A%0A      
-  
 this.setStat
@@ -2489,18 +2489,16 @@
 State(%7B%0A
-  
         
@@ -2578,21 +2578,11 @@
     
- 
- 
 %7D)%0A
-      %7D%0A
     
@@ -2605,35 +2605,74 @@
 his.
+setState(%7B%0A        
 select
+ed
 Task
-AndSetComments();
+: this.props.tasks.first()%0A      %7D)
 %0A   
@@ -3772,68 +3772,8 @@
  %7D%0A%0A
-  // TODO - Better handle it on the redux level and on each%0A
   //
@@ -3848,32 +3848,50 @@
 omments(task) %7B%0A
+    if (task) %7B%0A  
     this.props.h
@@ -3930,16 +3930,80 @@
 d%22)%7D%60);%0A
+    %7D%0A    else %7B%0A      this.props.history.push(%60/%60);%0A    %7D%0A    %0A
   %7D%0A%0A  r

fix close task