/*
FileName:UserPendingMyTask.js
Version:1.0.0
Purpose:Getting the List of user pending my task list
Devloper:Mahesh ,Naveen Kumar (Offline)
*/

import React, { Component } from 'react';
import moment from "moment";
import { ToastAndroid, Platform, StyleSheet, TextInput, Text, View, Alert, Dimensions, LayoutAnimation, UIManager, TouchableOpacity, FlatList, Image } from 'react-native';
import { Left, Button, Container, Header, Content, Item, Input } from 'native-base';
import Icon from 'react-native-vector-icons/FontAwesome';
import AsyncStorage from '@react-native-community/async-storage';
import { widthPercentageToDP as wp, heightPercentageToDP as hp } from 'react-native-responsive-screen';
import RadioGroup from 'react-native-radio-button-group';
import Modal from "react-native-simple-modal";
import { Collapse, CollapseHeader, CollapseBody } from "accordion-collapse-react-native";
import { API } from "../WebServices/RestClient";
import * as Progress from 'react-native-progress';
import NetInfo from '@react-native-community/netinfo';
import Snackbar from 'react-native-snackbar';
import Toast from 'react-native-whc-toast';
import log from '../LogFile/Log';
import { NavigationEvents } from 'react-navigation';
//import Checkbox from 'react-native-modest-checkbox'
import Main from '../Maintenance/Main';
const check = new Main()
import UserDatabase from '../OfflineDB/UserDatabase';
import RadioButtonRN from 'radio-buttons-react-native';

import { SUBTASK, TITLE, DESCRIPTION, TARGETTIME, TASKSTATUS, ASSIGNEDON, STATUS, ASSIGNED_BY, UPDATEDON, TIMELEFT, MODIFY, UPDATESTATUS } from '../CommonComponents/Header';

const db = new UserDatabase();
import {
  BallIndicator,
  BarIndicator,
  DotIndicator,
  MaterialIndicator,
  PacmanIndicator,
  PulseIndicator,
  SkypeIndicator,
  UIActivityIndicator
} from 'react-native-indicators';

// var today = new Date();
// date=today.getDate() + "/"+ parseInt(today.getMonth()+1) +"/"+ today.getFullYear();
// console.log(date);

//alert(date);
class ListItem extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      isLoading: true,
      expanded: false,
      dataSource2: [],
    }
    this.getMessages();

    if (Platform.OS === 'android') {
      UIManager.setLayoutAnimationEnabledExperimental(true);
    }
  }

  changeLayout = () => {
    LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut);
    this.setState({ expanded: !this.state.expanded });
  }

  

  getMessages() {
    log("Info", " getMessages(role, userToken, cropcode) is used getting task related messages");
    // const groupId = this.state.subtaskId;
    // console.warn("getmessages");
    // alert("Testing")
    AsyncStorage.multiGet(["cropcode", "userToken"], (err, response) => {
      const cropcode = response[0][1];
      const userToken = response[1][1];
      this.setState({ userid: userToken });
      AsyncStorage.getItem("projectId", (err, res) => {
        const projectId = res;
        // console.warn("userToken"+userToken)
        // console.warn("cropcode"+cropcode)

        NetInfo.fetch().then(state => {
          if (state.type == "none") {
            log("Warn", "No internet connection");
            Snackbar.show({
              title: 'No Internet Connection',
              backgroundColor: 'red',
              duration: Snackbar.LENGTH_LONG,
            });
          }
          else {
            fetch(API + "user_story_chat.php",
              {
                method: 'POST',
                headers: {
                  Accept: 'application/json',
                  'Content-Type': 'application/json',
                },
                body: JSON.stringify({

                  action: "getAllTaskMessages",
                  corp_code: cropcode,
                  // projectId: projectId
                  // sendBy: userToken,


                })
              })
              .then((response) => response.json())
              .then((responseJson) => {
                console.warn("Messages For chat application" + JSON.stringify(responseJson.data));
                // alert("Send By Name" + JSON.stringify(responseJson.data));
                console.warn("Messages from users" + JSON.stringify(responseJson))
                // console.warn("Send By Name" + JSON.stringify(responseJson.data))
                if (responseJson.status === 'True') {

                  console.warn("Setted Data")



                  this.setState({
                    dataSource2: responseJson.data,
                  });
                  console.warn("Method data" + responseJson.data.sendBy)
                }
                else {
                  console.warn("Empty  Data")
                  this.setState({
                    dataSource2: '',
                  });
                }
              })
              .catch((error) => {
                console.error(error);
                log("Error", "getting task related messages error");
              });

          }
        });
      });
    });
  }


  //Navigates to TaskChat Screen
  TaskChat(taskid, action, msgCount) {
    console.warn("msgCount" + msgCount);
    console.warn("taskid" + taskid);
    // alert(taskid)
    // alert("taskid" + taskid)
    log("Info", "UserPendingMyTasks:TaskChat(item, index) used to navigate to taskchat")
    this.props.navigation.navigate("TaskChat", { id: taskid, action: "maintask", sno: msgCount });
  }


  render() {


    const { item } = this.props;

    console.log("datecurrent" + item.cDate)

    console.log("target date" + item.targetDate);

    var currentdate = new Date();
    var datetime = currentdate.getFullYear() + "-"
      + (currentdate.getMonth() + 1) + "-"
      + currentdate.getDate() + "  "
      + currentdate.getHours() + ":"
      + currentdate.getMinutes() + ":"
      + currentdate.getSeconds();
    // console.warn("date" + item.cDate + "update" + item.targetDate);
    //console.warn(datetime > item.targetDate);
    //console.warn("Numbers"+item.activeStatus);
    // const radio1 = <RadioGroup
    //   options={[
    //     {
    //       id: '1',
    //       labelView: (
    //         <Text>
    //           <Text style={{ color: 'Green' }}></Text>
    //         </Text>
    //       ),
    //     },

    //   ]}
    //   activeButtonId={item.activeStatus}
    //   value={item.activeStatus}
    //   onChange={(options) => this.userActiveTaskStatusUpdate()}
    // />
    // const radio2 = <RadioGroup
    //   options={[
    //     {
    //       id: '0',
    //       labelView: (
    //         <Text>
    //           <Text style={{ color: 'white' }}></Text>
    //         </Text>
    //       ),
    //     },

    //   ]}
    //   activeButtonId={item.activeStatus}
    //   value={item.activeStatus}
    //   onChange={(options) => this.userActiveTaskStatusUpdate()}
    // />
    let Dependency = <View style={styles.box1}>
      <View style={{ flexDirection: 'row', width: wp('50%') }}>
        <Text style={styles.signUpText000} >Dependency:</Text>
        <Text style={styles.signUpText11111} >{item.dependencyTitle}</Text>
      </View>
      <View style={{ width: wp('40%'), paddingRight: 20 }}>
        <Text style={styles.signUpText002} >Dependent:{item.dependencyUser}</Text>
      </View>
    </View>
    let button2;
    const { usertype } = this.props;
    if (item.assignedBy === usertype) {
      button2 =
        <View style={{ flexDirection: 'row', justifyContent: 'flex-end', alignItems: 'center' }}>
          {/* <Text>Reasign</Text> */}
          <TouchableOpacity onPress={() => { this.props.Module() }} style={{ marginLeft: 10, width: 80, backgroundColor: 'black' }}><Text style={{ color: '#fff', textAlign: 'center' }}>{MODIFY}</Text></TouchableOpacity>

          {/* <Text style={{ width: 80, backgroundColor: 'black', marginLeft: 10, }} onPress={() => { this.props.Module() }}>Reassign</Text> */}

        </View>

    } else {
      button2 = null;


    }

    // var data1=this.state.dataSource1;
    const getMessagesCount = (id, msg, empId) => {
      //  console.warn("ids"+JSON.stringify(data1) +id)

      //  var msg=this.state.dataSource1;
      // console.warn("Datasource and id send by"+JSON.stringify(data1.sendBy))
      // let msgCount = data1.filter(message => message.sendBy === id).map((messages, i) => {
      let msgCount = msg.filter(message => message.readBy.split(",").indexOf(empId) === -1 && message.messagedBy !== empId && message.groupId === id).map((messages, i) => {

        return i, messages

      })
      // alert("iiiiiiii" + id)

      console.warn("iiiiiiii" + id)
      console.warn("msgcount" + msgCount)

      return (
        // console.warn("iiiiiiii" + msgCount),
        <View>
          <Text style={{ color: 'red', }}> {msgCount.length > 0 ? msgCount.length : null} </Text>
          {/* {msgCount.length > 0 ? msgCount.length : null} */}
          {
            msgCount.length > 0 ?

              <TouchableOpacity style={{ marginTop: -20, marginLeft: 18 }} onPress={() => { this.TaskChat(id, "maintask", msgCount) }}>
                <Image style={{ width: 25, height: 25 }} source={require('../Images/chat.png')} />
              </TouchableOpacity>
              :
              <TouchableOpacity style={{ marginTop: -20, marginLeft: 18 }} onPress={() => { this.TaskChat(id, "maintask", msgCount) }}>
                <Image style={{ width: 25, height: 25, }} source={require('../Images/chat.png')} />

              </TouchableOpacity>

          }

        </View>
      )

    }



    return (

      <View>

        {/* <Collapse style={[item.cDate >= item.targetDate ? styles.container : styles.container1]}>

          <CollapseHeader style={styles.boxheader}> */}
        <View style={[item.cDate >= item.targetDate ? styles.container : styles.container1]}>
          <View style={styles.boxheader}>
            <TouchableOpacity activeOpacity={0.8} onPress={this.changeLayout} >
              {/* <CollapseHeader style={[item.timeLeft<0?styles.boxheader:styles.boxheader1]} > */}


              <View style={{ flexDirection: 'row' }}>
                <View style={{ flexDirection: 'row', width: wp('30%') }}>
                  {/* <Text style={styles.signUpText0} >Id:</Text> */}
                  <Text style={styles.signUpText0} >{(this.props.cropcode).substring(0, 3).toUpperCase()}:</Text>
                  <Text style={styles.signUpText1} >{item.story_id.substring(0, 5).toUpperCase()}</Text>

                </View>
                <View>

                </View>
                <View style={{ alignItems: 'flex-end', width: '70%' }}>
                  <Text >{item.assignedto}</Text>
                </View>
              </View>


              <View style={styles.box1}>
                <View style={{ flexDirection: 'row', width: wp('90%') }}>
                  <Text style={styles.signUpText00} >{TITLE}:</Text>
                  <Text style={styles.signUpText11} >{item.title}</Text>
                </View>
              </View>
              <View style={{ flexDirection: 'row', marginBottom: 10, marginTop: 10 }}>
                <View style={{ width: '90%', flexDirection: 'row', }}>
                  {getMessagesCount(item.us_id, this.state.dataSource2, this.props.empId)}
                  <TouchableOpacity onPress={this.props.Comments} style={{ marginLeft: 10 }}>
                    <Image style={{ width: 25, height: 25 }} source={require('../Images/comments.png')} />
                  </TouchableOpacity>
                </View>

                <View >
                  <TouchableOpacity style={{ marginRight: 10, }} onPress={(id) => this.props.openModal()}>
                    <Image style={{ width: 25, height: 25, }} source={require('../Images/agilemove.png')} />
                  </TouchableOpacity>
                </View>

              </View>
            </TouchableOpacity>
          </View>
          {/* </CollapseHeader> */}
          <View style={{ height: this.state.expanded ? null : 0, overflow: 'hidden' }}>
            <CollapseBody>
              <View style={{ flexDirection: 'row', paddingRight: 25, width: '85%' }}>
                <Text style={styles.signUpText44} >{DESCRIPTION} : </Text>
                <Text style={styles.signUpText33} >{item.subTaskDesc}</Text>
              </View>
              <View style={{ flexDirection: 'row', paddingRight: 25, width: '75%' }}>
                <Text style={styles.signUpText44} >Acceptance Criteria : </Text>
                <Text style={styles.signUpText33} >{item.acceptanceCriteria}</Text>
              </View>
              {/* <View style={styles.box1}>
                <View style={{ flexDirection: 'row', width: wp('48%') }}>
                  <Text style={styles.signUpText000} >{TARGETTIME}:</Text>
                  <Text style={styles.signUpText11111} >{item.targetDate}</Text>
                </View>
              </View> */}
              {/* <View style={{ flexDirection: 'row', paddingRight: 25, width: wp('80%') }}>
                <Text style={styles.signUpText44} >Story Progress:</Text>
                <Text style={styles.signUpText33} >{item.taskStatus}%Completed</Text>
              </View> */}
              <View style={styles.box1}>
                <View style={{ flexDirection: 'row' }}>
                  <Text style={styles.signUpText000} >{ASSIGNEDON} :</Text>
                  <Text style={styles.signUpText1101} >{moment(item.assignedDate).format('MM.DD.YYYY hh:mm:ss')}</Text>
                </View>
              </View>
              <View style={{ flexDirection: 'row', paddingRight: 25, width: wp('80%') }}>
                <Text style={styles.signUpText44} >{ASSIGNED_BY} :</Text>
                <Text style={styles.signUpText33} >{item.assignedby}</Text>
              </View>
              {/* <View style={{ flexDirection: 'row', paddingRight: 25, width: wp('80%') }}>
                <Text style={styles.signUpText44} >Assigned To:</Text>
                <Text style={styles.signUpText33} >{item.assignedto}</Text>
              </View> */}
              {/* <View style={{ flexDirection: 'row', paddingRight: 25, }}>
                <Text style={styles.signUpText44} >{STATUS}:</Text>
                <Text style={styles.signUpText33} >{item.taskStatusDesc}</Text>
              </View> */}
              {/* <View style={styles.box1}> */}
              {/* <View style={{ flexDirection: 'row', width: wp('45%') }}>
                  <Text style={styles.signUpText000} >{TIMELEFT}:</Text>
                  <Text style={styles.signUpText1101} >{item.timeLeft}</Text>
                </View> */}
              {/* <View style={{ flexDirection: 'row', width: wp('45%'), }}>
                  <Text style={styles.signUpText000} >{UPDATEDON}:</Text>
                  <Text style={styles.signUpText1101} >{item.taskEndDate}</Text>
                </View> */}
              {/* </View> */}
              {/* {item.dependencyUser == 'NA' ? null : Dependency} */}
              <View style={{ flexDirection: 'row', justifyContent: 'flex-end', alignItems: 'center' }}>
                {/* <TouchableOpacity onPress={this.props.RoadBlock} style={{ width: 20, backgroundColor: 'black' }}><Text style={{ color: '#fff', textAlign: 'center' }}>?</Text></TouchableOpacity> */}
                {/* <TouchableOpacity onPress={() => this.props.openModal()} style={{ width: 130, backgroundColor: 'black', marginLeft: 10, }}><Text style={{ color: '#fff', textAlign: 'center' }}>{UPDATESTATUS}</Text></TouchableOpacity> */}
                {/* <Icon size={22} style={{ paddingLeft: 10, paddingTop: 4 }} name="comments" onPress={() => { this.props.TaskChat() }}></Icon> */}
                {button2}

              </View>

              <View
                style={{
                  borderBottomColor: '#C0C0C0',
                  marginBottom: 10,
                }}
              />
            </CollapseBody>
          </View>
        </View>

      </View>
    )
    // return(
    //   <View style={styles.buttonContainer}>
    //     <View style={{flexDirection:'row'}}>
    //     <View style={{width:wp('60%'),flexDirection:'row'}}>
    //       <Text style={{color:'green',fontSize:13,}}>Task:</Text>
    //       <Text style={{color:'green',fontSize:13,}}>  {item.subTaskId} -  {item.mainTaskTitle}</Text>
    //     </View>
    //     <View style={{width:wp('4%')}}></View>
    //     <View style={{width:wp('30%'),flexDirection:'row',justifyContent:'flex-end'}}>
    //       <Text style={{fontSize:14,color:'black'}}>{item.status} </Text>
    //     </View>
    //     </View>
    //     <View style={{flexDirection:'row'}}>
    //     <View style={{width:wp('60%'),flexDirection:'row'}}>
    //       <Text style={{color:'black',fontSize:13,}}>Title:</Text>
    //       <Text style={{color:'black',fontSize:13,}}> {item.taskTitle}</Text>
    //     </View>
    //     <View style={{width:wp('4%')}}></View>
    //     <View style={{width:wp('30%'),flexDirection:'row',justifyContent:'flex-end'}}>
    //     {item.activeStatus === 1 ? radio2 : radio1}
    //     </View>
    //     </View>

    //     <View style={{flexDirection:'row'}}>
    //     <View style={{width:wp('90%'),flexDirection:'row'}}>
    //       <Text style={{color:'black', fontSize: hp('2%')}}>Description :</Text>
    //       <Text style={{color:'black', fontSize: hp('2%'),}}> {item.subTaskDesc}</Text>
    //     </View>
    //     {/* <View style={{width:wp('4%')}}></View>
    //     <View style={{width:wp('30%'),flexDirection:'row',justifyContent:'flex-end'}}>
    //     {item.activeStatus === 1 ? radio2 : radio1}
    //     </View> */}
    //     </View>
    //     <View style={{flexDirection:'row',}}>
    //     <View style={{width:wp('40%'),flexDirection:'row',paddingRight:wp('8%')}}>
    //       <Text style={{color:'black', fontSize: hp('2%')}}>Target Time:</Text>
    //       <Text style={{color:'black', fontSize: hp('2%')}}> {item.targetDate}</Text>
    //     </View>
    //     <View style={{width:wp('13%')}}>
    //       <Text></Text>
    //     </View>
    //     <View style={{width:wp('40%'),flexDirection:'row',}}>
    //     <Text style={{color:'black', fontSize: hp('2%')}}>Target Status:</Text>
    //       <Text style={{color:'black', fontSize: hp('2%')}}>{item.taskStatus}% completed</Text>
    //     </View>
    //     </View>
    //     <View style={{height:hp('1%'),backgroundColor:'black'}}/>
    //   </View>
    // )
  }
}
export default class Pending extends Component {
  static navigationOptions = () => {
    return {
      tabBarOnPress({ navigation, defaultHandler }) {
        navigation.state.params.onTabFocus();
        defaultHandler();
        this.onRefresh();
      }
    };
  }

  constructor(props) {

    super(props);
    // console.log(this.props.navigation.state.params)
    props.navigation.setParams({
      onTabFocus: this.handleTabFocus
    });
    this.state = {
      isLoading: true,
      dataSource: [],
      isFetching: false,
      result: '',
      description: '',
      taskcompleteStatus: '',
      activeStatus: '',
      error1: '',
      error2: '',
      date: '',
      // moduleId:''
    }

    AsyncStorage.getItem("moduleId", (err, res) => {
      this.setState({ moduleId: res });
      // alert(this.state.moduleId)

    });
    //  this.getActive();
    this.arrayholder = [];
  }

  handleTabFocus = () => {
    this.onRefresh();
  };
  //Dialog Actions start
  modalDidOpen = () => {
    AsyncStorage.getItem("role", (err, res) => {
      this.setState({ role: res });

    });
    AsyncStorage.getItem("userToken", (err, res) => {
      this.setState({ userToken: res });

    });


  }

  modalDidClose = () => {
    this.setState({ open: false });
  };

  moveUp = () => this.setState({ offset: -1200 });

  resetPosition = () => this.setState({ offset: 0 });

  openModal = (item, index) => {
    this.setState({ item: item });
    this.setState({ open: true });
  }
  //Dialog Actions end

  //Navigates to RoadBlock Screen
  RoadBlock(item, index) {
    log("Info", "UserPendingMyTasks:RoadBlock(item, index) used to navigate to RoadBlock")
    this.props.navigation.navigate("RoadBlocks", { subtaskid: item.subTaskId });
  }

  // //Navigates to TaskChat Screen
  // TaskChat(taskid,action,msgCount) {
  //   console.warn("msgCount"+msgCount);
  //   console.warn("taskid"+taskid);
  //   log("Info", "UserPendingMyTasks:TaskChat(item, index) used to navigate to taskchat")
  //   this.props.navigation.navigate("TaskChat", { id: taskid, action: "maintask",sno:msgCount });
  // }

  //close the dialog
  closeModal = () => this.setState({
    open: false,
    taskcompleteStatus: '',
    error1: '', error2: '',
  });

  componentDidMount() {
    // this.getActiveSprints();
    AsyncStorage.getItem("userName", (err, res) => {
      this.setState({ usertype: res });
      console.warn(this.state.usertype);
    });
    AsyncStorage.getItem("userToken", (err, res) => {
      this.setState({ empId: res });
      console.warn(this.state.empId);
    });
    AsyncStorage.getItem("cropcode", (err, res) => {
      this.setState({ cropcode: res });
      console.warn(this.state.cropcode);
    });
    AsyncStorage.getItem("moduleId", (err, res) => {
      this.setState({ moduleId: res });
      console.warn(this.state.moduleId);
      // alert(this.state.moduleId)
    });
  
    log("Debug", "user pending mytask tasks screen is loaded at user side");
    NetInfo.fetch().then(state => {
      if (state.type == "none" || state.type == 'unknown' || state.type == 'undefined') {
        console.log(state.type);
        Snackbar.show({
          title: 'No Internet Connection',
          backgroundColor: 'red',
          duration: Snackbar.LENGTH_LONG,
        });
        this.getSubtaskListPending()
     
        // this.getPendingtasksList();
        // this.getActive(); //For pending subtaskslist from offline
      } else {
        //to get the user pending my task list
        // this.getActive(); //server
        this.getSubtaskListPending()

      }
    });

  }
//get ActiveSprints data
getActiveSprints() {
  log("Info", "UserProfile:GetStatus() method is used to get status of employee");
  AsyncStorage.getItem("empId", (err, res) => {
    const empId = res;
    AsyncStorage.getItem("cropcode", (err, res) => {
      const cropcode = res;
      AsyncStorage.getItem("emp_role", (err, res) => {
        const emp_role = res;
        AsyncStorage.getItem("projectId", (err, res) => {
          const projectId = res;
          NetInfo.fetch().then(state => {
            if (state.type == "none" || state.type == 'unknown' || state.type == 'undefined') {
              // console.log(state.type);
              Snackbar.show({
                title: 'No Internet Connection',
                backgroundColor: 'red',
                duration: Snackbar.LENGTH_LONG,
              });
              this.getOfflineActiveSprints("currentsprint")//Getting Current Sprint Backlogs in offline
              // this.getBacklogs("currentsprint") //Getting Current Sprint Backlogs in offline
            } else {

              fetch(API + 'getUpdateSprint.php', {
                method: 'POST',
                headers: {
                  Accept: 'application/json',
                  'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                  crop: cropcode,
                  // userType: emp_role,
                  // empId: empId,

                  action: "get_sprints",
                  projectId: projectId


                })
              })
                .then((response) => response.json())
                .then((responseJson) => {
                  //alert(JSON.stringify(responseJson.data))
                  // console.warn("getActiveSprint data" + JSON.stringify(responseJson.data));
                  if (responseJson.status == 'True') {
                    this.setState({
                      isLoading: false,
                      dataSource1: [...responseJson.data],
                      moduleId: responseJson.data[0].moduleId,
                      ideaId: responseJson.data[0].ideaId,
                      moduleDesc: responseJson.data[0].moduleDesc,
                      startDate: responseJson.data[0].startDate,
                      targetDate: responseJson.data[0].targetDate,
                      sprint_status: responseJson.data[0].sprint_status,

                    }, function () {
                      // In this block you can do something with new state.
                    });
                    AsyncStorage.setItem('moduleId', responseJson.data[0].moduleId);
                    AsyncStorage.setItem('ideaId', responseJson.data[0].ideaId);

                    this.getInvolvedEmployees(responseJson.data[0].moduleId)
                    this.getRequestedIdeas(responseJson.data[0].moduleId)

                  } else {
                    //For No Active Sprints
                    this.setState({
                      isLoading: false,
                      dataSource1: [],
                      moduleId: '',
                      moduleDesc: ''
                    })
                    log("Warn", "status of employee is not available");
                  }
                })
                .catch((error) => {
                  console.error(error);
                  log("Error", "error in  getting status of employee");
                });
            }
          });
        });
      });
    });
  });

}
  //to refresh the pending my task list 
  onRefresh() {
    this.setState({
      dataSource: [],
    })
    NetInfo.fetch().then(state => {
      if (state.type == "none" || state.type == 'unknown' || state.type == 'undefined') {
        console.log(state.type);
        Snackbar.show({
          title: 'No Internet Connection',
          backgroundColor: 'red',
          duration: Snackbar.LENGTH_LONG,
        });
        this.getPendingtasksList(); //For pending subtaskslist from offline
      } else {
        this.getSubtaskListPending();
        //to get the user pending my task list
        // this.getActive();
      }
    });

  }


  componentWillReceiveProps(nextProps) {
    NetInfo.fetch().then(state => {
      if (state.type == "none" || state.type == 'unknown' || state.type == 'undefined') {
        console.log(state.type);
        Snackbar.show({
          title: 'No Internet Connection',
          backgroundColor: 'red',
          duration: Snackbar.LENGTH_LONG,
        });
        this.getPendingtasksList(); //For pending subtaskslist from offline
      } else {
        //to get the user pending my task list
        // this.getActive();
        this.getSubtaskListPending();
        // this.onRefresh();
      }
    });

  }
  //For pending subtaskslist from offline
  getPendingtasksList() {
    AsyncStorage.getItem("cropcode", (err, res) => {
      const projectName = res;
      AsyncStorage.getItem("moduleId", (err, res) => {
        const moduleId = res;
        db.pendingSubtasksList(projectName, 'todo', moduleId).then((data) => {
          console.warn("peendingtaskData" + JSON.stringify(data))
          // console.warn(data[0].empid)/
          this.setState({
            dataSource: data,
            isLoading: false,
          });
          this.arrayholder = data;
        }).catch((err) => {
          // console.log(err);
          this.setState = {
            isLoading: false
          }
        })
      });
    });
  }

  //For store pending subtaskslist from offline
  addPendingSubtasks(data, cropcode) {
    console.warn("hello" + JSON.stringify(data));
    db.addPendingSubtasks(data, cropcode, 'todo').then((result) => {
      console.log(result);
    }).catch((err) => {
      console.log(err);
    })
  }


  //Checking the Validations
  isValid() {
    const { taskcompleteStatus, description } = this.state;
    let valid = true;
    if (taskcompleteStatus.length === 0) {
      this.setState({ error1: 'Enter Status ' });
    }
    if (taskcompleteStatus.length === 0) {
      this.setState({ error1: 'Enter Status ' });
    }
    else if (description.length === 0) {
      this.setState({ error2: 'Enter Description', taskcompleteStatus: '', });
    }
    else {
      return valid;
    }
  }

  //to get the active sprint list
  getActive() {
    log("Info", "UserCompletedMyTask:userCompletedMyTasks() method is used to get completed my tasks at user side");
    AsyncStorage.getItem("cropcode", (err, res) => {
      const cropcode = res;

      AsyncStorage.getItem("userToken", (err, res) => {
        const empId = res;

        AsyncStorage.getItem("emp_role", (err, res) => {
          const emp_role = res;
          //Checking the Internet Connection
          NetInfo.addEventListener(state => {
            if (state.type == "none" || state.type == 'unknown' || state.type == 'undefined') {
              console.log(state.type);
              Snackbar.show({
                title: 'No Internet Connection',
                backgroundColor: 'red',
                duration: Snackbar.LENGTH_LONG,
              });
            } else {

              fetch(API + 'getUpdateSprint.php',
                {
                  method: 'POST',
                  headers: {
                    Accept: 'application/json',
                    'Content-Type': 'application/json',
                  },
                  body: JSON.stringify({
                    crop: cropcode,
                    action: "get_sprints",
                    // userType: emp_role,
                    // empId: empId,
                    // moduleId:moduleId,
                  })
                })
                .then((response) => response.json())
                .then((responseJson) => {
                  console.log(responseJson);
                   //alert(JSON.stringify(responseJson))
                  console.warn("module id setting" + JSON.stringify(responseJson))
                  if (responseJson.connection === 'connected ') {
                    if (responseJson.status === 'True') {
                      this.setState({
                        isLoading: false,
                        moduleId: responseJson.data[0].moduleId,
                      }, function () {
                        // In this block you can do something with new state.
                      });
                      AsyncStorage.setItem('moduleId', responseJson.data[0].moduleId);

                      this.getSubtaskListPending(responseJson.data[0].moduleId)
                    } else {

                      log("Info", "No ToDo List");
                      // this.arrayholder = [];
                      this.setState({
                        isLoading: false,
                        dataSource: [],
          
                          moduleId: '',
                          moduleDesc: ''
                       
                      })
                      Snackbar.show({
                        title: 'No ToDo List',
                        backgroundColor: '#3BB9FF',
                        duration: Snackbar.LENGTH_LONG,
                      });
                    }
                  }
                  else {
                    this.props.navigation.navigate('Maintenance');
                  }
                })
                .catch((error) => {
                  console.error(error);
                  check.Maintenance();
                  log("Error", "Error in getting of completed my tasks at user side");
                });

            }
          });

        });

      });

    });
  }


  //to get the user pending my task list 
  getSubtaskListPending() {


    log("Info", "UserPendingMyTask:getSubtaskListPending() method is used to get pending my tasks at user side");
    AsyncStorage.getItem("cropcode", (err, res) => {
      const cropcode = res;
      AsyncStorage.getItem("userToken", (err, res) => {
        const empId = res;
        AsyncStorage.getItem("emp_role", (err, res) => {
          const emp_role = res;
          AsyncStorage.getItem("moduleId", (err, res) => {
            const moduleId = res;
            AsyncStorage.getItem("projectId", (err, res) => {
              const projectId = res;


              // alert("Sprint Id"+moduleId)

              //Checking the Internet Connections
              NetInfo.addEventListener(state => {
                if (state.type == "none" || state.type == "undefined" || state.type == "unknown") {
                  console.warn(state.type);
                  Snackbar.show({
                    title: 'No Internet Connection',
                    backgroundColor: 'red',
                    duration: Snackbar.LENGTH_LONG,
                  });
                } else {

                  fetch(API + 'get_user_stories.php',
                    {
                      method: 'POST',
                      headers: {
                        Accept: 'application/json',
                        'Content-Type': 'application/json',
                      },
                      body: JSON.stringify({
                        crop: cropcode,
                        action: "pending",
                        // userType: emp_role,
                        // empId: empId,
                        moduleId: moduleId,
                        projectId: projectId,
                      })
                    })
                    .then((response) => response.json())
                    .then((responseJson) => {
                      // alert(JSON.stringify(responseJson))
                      console.warn("Pending list todo" + JSON.stringify(responseJson))
                      if (responseJson.connection === 'connected ') {
                        if (responseJson.status === 'True') {



                          var toDoList = [];
                          var doingList = [];
                          // console.log(response)
                          responseJson.data.map((pending) => {
                            return (
                              (pending.activeStatus === "0") ? toDoList.push(pending) : (pending.activeStatus === "1") ? doingList.push(pending) : null
                            );
                          })

                          // alert(JSON.stringify(responseJson.data))
                          this.addPendingSubtasks(toDoList, cropcode) //For store pending subtaskslist from offline
                          this.setState({
                            isLoading: false,
                            dataSource: toDoList,
                            isFetching: false
                          }, function () {
                          });
                          this.arrayholder = responseJson.data;
                          // this.arrayholder = toDoList;
                        }
                        else {
                          log("Info", "no pending my tasks at user side");
                          this.arrayholder = [];
                          this.setState({
                            isLoading: false,
                            dataSource: [],
                          })
                          Snackbar.show({
                            title: 'No Pending Backlogs',
                            backgroundColor: '#3BB9FF',
                            duration: Snackbar.LENGTH_LONG,
                          });
                        }
                      } else {
                        this.props.navigation.navigate('Maintenance');
                      }
                    })
                    .catch((error) => {
                      check.Maintenance();
                      this.setState({
                        isLoading: false,
                      })
                      console.error(error);
                      log("Error", "Error in getting of pending my tasks at user side");
                    });
                }
              });
            });
          });
        });
      });

    });

  }

  //check dependency 
  userTaskUpdate = () => {
    log("Info", "UserPendingMyTask:userTaskUpdate() method is used to check dependency");
    const { item, } = this.state;
    const dependency = item.dependencyId;
    if (dependency == "NA") {
      this.updateStatus();
    } else {
      this.updateStatus();
      // alert("You can't update until your dependency task completed");
    }
  }

  // if dependency not exit this method will executes
  updateStatus = () => {
    log("Info", "UserPendingMyTask:userTaskUpdate() method is used to update  pending subtasks tasks at user side");
    const { item, taskStatus, description, taskcompleteStatus } = this.state;
    //task completed status 
    if (taskcompleteStatus == 100) {
      this.setState({
        taskStatus: (Number(taskcompleteStatus)),
        taskcompleteStatus: (Number(taskcompleteStatus) / 100).toString(),
      })
    }
    else {
      this.setState({
        taskStatus: (Number(taskcompleteStatus) * 100)
      })
    }
    //Checking the Internet Connections
    NetInfo.fetch().then(state => {
      if (state.type == "none" || state.type == "undefined" || state.type == "unknown" || state.type == "cell") {
        console.log(state.type);
        Snackbar.show({
          title: 'No Internet Connection',
          backgroundColor: 'red',
          duration: Snackbar.LENGTH_LONG,
        });
      } else {
        if (this.isValid()) {
          const taskcomplete = this.state.taskcompleteStatus;
          AsyncStorage.getItem("cropcode", (err, res) => {
            const cropcode = res;
            fetch(API + 'getSubtasks.php',
              {
                method: 'POST',
                headers: {
                  Accept: 'application/json',
                  'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                  crop: cropcode,
                  action: "update",
                  task_id: item.id,
                  dependencyId: item.dependencyId,
                  task_status: this.state.taskStatus,
                  task_status_desc: description,
                  task_complete_status: taskcomplete,
                  mainTaskId: item.mainTaskid,
                })

              })
              .then((response) => response.json())
              .then((responseJson) => {
                // console.log(JSON.stringify(responseJson))

                if (responseJson.status === 'True') {
                  alert("Your Task is Updated Successfully");
                  this.getSubtaskListPending();//to get the user pending my task list

                  this.setState({
                    isLoading: false,
                    dataSource: responseJson.data,
                    isFetching: false
                  }, function () {
                  });

                } else {
                  log("Info", "no pending my tasks at user side");
                }

              })
              .catch((error) => {
                console.error(error);
                log("Error", "Error in getting of pending my tasks at user side");
              });
          });
          this.closeModal();
        }
      }
    });
  }

  Module(item, index) {
    let time = item.estimatedHours;

    let days1 = (Number(time / 24)).toString().split(".");
    days = days1[0];
    //alert(days1[0]);
    hours = Number(time % 24);
    console.log(item);
    console.log(index);
    // alert(days+"    "+hours+"     "+item.estimatedHours);

    //navigate to ModifySubtask
    this.props.navigation.navigate('ModifySubTask', {
      callHome: this.getSubtaskListPending.bind(this),
      action: 'modify', IdeaId: this.props.navigation.state.params.IdeaId, subTask: item.taskTitle, description: item.subTaskDesc, person: item.assignedTo,
      name: item.assignedBy, subTaskId: item.subTaskId, days: days, hours: hours
    });

  }

  move1(text) {
    if (Number(text) >= 1 && Number(text) <= 100) {
      let actionbar = Number(text / 100);
      return actionbar;
    }
    else {

      return alert("Status upto 100 % only"),
        this.setState({
          taskcompleteStatus: ''
        }),
        this.state.taskcompleteStatus;

    }
  }





  userActiveTaskStatusUpdate = () => {

    Alert.alert(
      'Alert..!',
      'Do you want to move task into In Progress',
      [
        {
          text: 'No',
          onPress: () => console.log('Cancel Pressed'),
          style: 'cancel',
        },
        { text: 'Yes', onPress: () => this.updateActiveTaskStatus() },
      ],
      { cancelable: false },
    );
  }

  userActiveTaskStatusUpdate1 = (todoStoryId,assignedTo,inProgressStoryId,project_name,story_title) => {
    const inProgressStoryId1=inProgressStoryId.substring(0, 5).toUpperCase();

    Alert.alert(
      'Alert..!',
      "User has "+inProgressStoryId1+"In Progress on "+project_name+" Confirm if you want to User Story (" +story_title+ ") into In Progress",
      [
        {
          text: 'Cancel',
          onPress: () => console.log('Cancel Pressed'),
          style: 'cancel',
        },
        { text: 'Confirm', onPress: () => this.updateActiveTaskStatus1(todoStoryId,assignedTo,inProgressStoryId) },
      ],
      { cancelable: false },
    );
  }



  // //check Task active status 
  // userActiveTaskStatusUpdate = () => {

  //   console.warn(this.props.item.id);
  //   log("Info", "userActiveTaskStatusUpdate() method is used to check the active status of subtask");
  //   const { item } = this.props;
  //   const activeStatus = item.activeStatus;

  //   if (activeStatus == 0) {
  //     this.updateActiveTaskStatus();

  //   } else {
  //     this.updateActiveTaskStatus();

  // alert("You can't update until your dependency task completed");

  //     log("Warn", "You can't update until your dependency task completed");
  //   }
  // }

  // if dependency not exit this method will executes
  updateActiveTaskStatus = () => {
    log("Info", "updateActiveTaskStatus() method is used to make subtask as active");
    // const { item, taskStatus, description, taskcompleteStatus, } = this.props;
    const { item, } = this.state;
    const message = "User story in progress";
    //Time();
    NetInfo.fetch().then(state => {
      if (state.type == "none" || state.type == "undefined" || state.type == "unknown") {
        console.log(state.type);
        Snackbar.show({
          title: 'No Internet Connection',
          backgroundColor: 'red',
          duration: Snackbar.LENGTH_LONG,
        });
      } else {
        AsyncStorage.getItem("cropcode", (err, res) => {
          const cropcode = res;
          AsyncStorage.getItem("empId", (err, res) => {
            const empId = res;
            fetch(API + 'manage_userstories.php',
              {
                method: 'POST',
                headers: {
                  Accept: 'application/json',
                  'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                  crop: cropcode,
                  action: "activate_user_story",
                  story_id: item.id,
                  empId: empId,
                })
              })
              .then((response) => response.json())
              .then((responseJson) => {
                // console.log(JSON.stringify(responseJson))
                // alert( JSON.stringify(responseJson))

                console.warn(responseJson)
                // alert( JSON.stringify(responseJson))
                if (responseJson.status === 'true') {
                  // alert(responseJson.message)
                  this.addCommentUserStory(message, item.id, "1")

                }
               else if (responseJson.status === 'true1') {
                // alert(responseJson.inprogress_story_title);
                  // if (responseJson.message === 'Active UserStory is found') {
                    // alert(responseJson.message)
                    this.userActiveTaskStatusUpdate1(item.id,responseJson.assignedTo,responseJson.data,responseJson.project_name,responseJson.story_title,)
                  // }
                  // else {
                  //   this.addCommentUserStory(message, item.id, "1")
                  
                  // }

                  // alert("Success");
                } else {

                  new Pending().onRefresh();

                  alert("You not able active this task untill complete your activated task");

                  log("Warn", "You not able active this task untill complete your activated task");
                }
              })
              .catch((error) => {
                console.error(error);
                log("Error", "Error in making subtask as active");
              });
          });
          this.closeModal();
        });
      }
    });
  }
// if dependency not exit this method will executes
updateActiveTaskStatus1 = (todoStoryId,assignedTo,inProgressStoryId) => {
  log("Info", "updateActiveTaskStatus() method is used to make subtask as active");
  // const { item, taskStatus, description, taskcompleteStatus, } = this.props;
  // alert(assignedTo)
  // const { todoStoryId,assignedTo,inProgressStoryId } = this.state;
  const message = "User story in progress";
  //Time();
  NetInfo.fetch().then(state => {
    if (state.type == "none" || state.type == "undefined" || state.type == "unknown") {
      console.log(state.type);
      Snackbar.show({
        title: 'No Internet Connection',
        backgroundColor: 'red',
        duration: Snackbar.LENGTH_LONG,
      });
    } else {
      AsyncStorage.getItem("cropcode", (err, res) => {
        const cropcode = res;
        AsyncStorage.getItem("empId", (err, res) => {
          const empId = res;
          // alert("empId"+this.state.empId)
          fetch(API + 'manage_userstories.php',
            {
              method: 'POST',
              headers: {
                Accept: 'application/json',
                'Content-Type': 'application/json',
              },
              body: JSON.stringify({
                crop: cropcode,
                empId: this.state.empId,
                todoStoryId:todoStoryId,
                inprogressStoryId:inProgressStoryId,
                action: "change_userstory_status",
                assignedTo:assignedTo
              })
            })
            .then((response) => response.json())
            .then((responseJson) => {
              console.warn(responseJson)
              if (responseJson.status === 'true') {
                // alert(responseJson.message)
                this.addCommentUserStory(message, todoStoryId, "1")

                alert("Updated Successfully");
              } else {

                new Pending().onRefresh();

                alert("You not able active this task untill complete your activated task");

                log("Warn", "You not able active this task untill complete your activated task");
              }
            })
            .catch((error) => {
              console.error(error);
              log("Error", "Error in making subtask as active");
            });
        });
        this.onRefresh();
      });
    }
  });
}

  // if dependency not exit this method will executes
  addCommentUserStory = (message, subtaskid, cardId) => {
    console.warn("message" + message)
    console.warn("subtaskid" + subtaskid)
    console.warn("cardId" + cardId)
    AsyncStorage.getItem("projectId", (err, res) => {
      const projectId = res;

      log("Info", "updateActiveTaskStatus() method is used to make subtask as active");
      // const { subtaskid, taskStatus, description, taskcompleteStatus, } = this.props;
      // const message="User story in progress";
      //Time();
      NetInfo.fetch().then(state => {
        if (state.type == "none" || state.type == "undefined" || state.type == "unknown") {
          console.log(state.type);
          Snackbar.show({
            title: 'No Internet Connection',
            backgroundColor: 'red',
            duration: Snackbar.LENGTH_LONG,
          });
        } else {
          AsyncStorage.getItem("cropcode", (err, res) => {
            const cropcode = res;
            AsyncStorage.getItem("userToken", (err, res) => {
              const empId = res;
              console.warn("empId" + empId)
              fetch(API + 'story_comments.php',
                {
                  method: 'POST',
                  headers: {
                    Accept: 'application/json',
                    'Content-Type': 'application/json',
                  },
                  body: JSON.stringify({
                    corp: cropcode,
                    action: "add_story_comment",
                    storyId: subtaskid,
                    userId: empId,
                    message: message,
                    cardId: cardId,
                    projectId: projectId

                  })
                })
                .then((response) => response.json())
                .then((responseJson) => {
                  console.warn(responseJson)
                  if (responseJson.status === 'True') {
                    // this.props.navigation.navigate('Pending');
                    this.onRefresh();
                    // this.getSubtaskListPending();
                    // alert("Success");
                  } else {

                    new Pending().onRefresh();

                    alert("You not able active this task untill complete your activated task");

                    log("Warn", "You not able active this task untill complete your activated task");
                  }
                })
                .catch((error) => {
                  console.error(error);
                  log("Error", "Error in making subtask as active");
                });
            });
          });
        }
      });
    });
  }
//Navigates to Comments Screen
Comments(item, index) {
  log("Info", "UserInprogressMyTasks:Comments(item, index) used to navigate to Comments")
  this.props.navigation.navigate("Comments", { subtaskid: item.story_id });
}
  FlatListItemSeparator = () => {
    return (
      <View
        style={{
          width: "100%",
          backgroundColor: "#000",
        }}
      />
    );
  }

  _listEmptyComponent = () => {
    return (
      <View>
        <Text></Text>
      </View>
    )
  }

  //to filter the search data in search area
  // SearchFilterFunction(text) {
  //   log("Info", "UserPendingMyTask:SearchFilterFunction(text) for search functionality");
  //   console.log(text);
  //   try {
  //     const newData = this.arrayholder.filter(function (item) {
  //       const subTaskId = item.subTaskId.toUpperCase()
  //       const subTaskId1 = text.toUpperCase()
  //       const mainTaskTitle = item.mainTaskTitle.toUpperCase()
  //       const mainTaskTitle1 = text.toUpperCase()
  //       const taskTitle = item.taskTitle.toUpperCase()
  //       const taskTitle1 = text.toUpperCase()
  //       const subTaskDesc = item.subTaskDesc.toUpperCase()
  //       const subTaskDesc1 = text.toUpperCase()
  //       const targetDate = item.targetDate.toUpperCase()
  //       const targetDate1 = text.toUpperCase()
  //       const taskStatus = item.taskStatus.toUpperCase()
  //       const taskStatus1 = text.toUpperCase()
  //       const assignedDate = item.assignedDate.toUpperCase()
  //       const assignedDate1 = text.toUpperCase()
  //       const assignedBy = item.assignedBy.toUpperCase()
  //       const assignedBy1 = text.toUpperCase()
  //       const timeLeft = item.timeLeft.toUpperCase()
  //       const timeLeft1 = text.toUpperCase()
  //       const dependencyId = item.dependencyId.toUpperCase()
  //       const dependencyId1 = text.toUpperCase()
  //       // const dependencyTitle = item.dependencyTitle.toUpperCase()
  //       // const dependencyTitle1 = text.toUpperCase()

  //       return subTaskId.indexOf(subTaskId1) > -1 ||
  //         mainTaskTitle.indexOf(mainTaskTitle1) > -1 ||
  //         taskTitle.indexOf(taskTitle1) > -1 ||
  //         subTaskDesc.indexOf(subTaskDesc1) > -1 ||
  //         targetDate.indexOf(targetDate1) > -1 ||
  //         taskStatus.indexOf(taskStatus1) > -1 ||
  //         assignedDate.indexOf(assignedDate1) > -1 ||
  //         assignedBy.indexOf(assignedBy1) > -1 ||
  //         timeLeft.indexOf(timeLeft1) > -1 ||
  //         dependencyId.indexOf(dependencyId1) > -1
  //       //   dependencyTitle.indexOf(dependencyTitle1) > -1

  //     })

  //     this.setState({
  //       dataSource: newData,
  //       text: text
  //     })
  //   }
  //   catch (error) {
  //     this.refs.toast.showBottom('No Results Found');
  //   }
  // }


  //to filter the search data in search are 
  // SearchFilterFunction(text) {
  //   log("Info", "UserCompletedMyTasks:SearchFilterFunction(text) for search functionality");
  //   console.log(text);
  //   try {
  //     const newData = this.arrayholder.filter(function (item) {
  //       const id = item.id.toUpperCase()
  //       const id1 = text.toUpperCase()
  //       const assignedto = item.assignedto.toUpperCase()
  //       const assignedto1 = text.toUpperCase()

  //       const taskTitle = item.taskTitle.toUpperCase()
  //       const taskTitle1 = text.toUpperCase()
  //       const subTaskDesc = item.subTaskDesc.toUpperCase()
  //       const subTaskDesc1 = text.toUpperCase()
  //       const targetDate = item.targetDate.toUpperCase()
  //       const targetDate1 = text.toUpperCase()
  //       const taskStatus = item.taskStatus.toUpperCase()
  //       const taskStatus1 = text.toUpperCase()
  //       const assignedDate = item.assignedDate.toUpperCase()
  //       const assignedDate1 = text.toUpperCase()
  //       const assignedBy = item.assignedBy.toUpperCase()
  //       const assignedBy1 = text.toUpperCase()
  //       // const timeLeft = item.timeLeft.toUpperCase()
  //       // const timeLeft1 = text.toUpperCase()
  //       // const dependencyId = item.dependencyId.toUpperCase()
  //       // const dependencyId1 = text.toUpperCase()
  //       // const dependencyTitle = item.dependencyTitle.toUpperCase()
  //       // const dependencyTitle1 = text.toUpperCase()

  //       return id.indexOf(id1) > -1 ||
  //         assignedto.indexOf(assignedto1) > -1 ||

  //         taskTitle.indexOf(taskTitle1) > -1 ||
  //         subTaskDesc.indexOf(subTaskDesc1) > -1 ||
  //         targetDate.indexOf(targetDate1) > -1 ||
  //         taskStatus.indexOf(taskStatus1) > -1 ||
  //         assignedDate.indexOf(assignedDate1) > -1 ||
  //         assignedBy.indexOf(assignedBy1) > -1
  //       // timeLeft.indexOf(timeLeft1) > -1 ||
  //       // dependencyId.indexOf(dependencyId1) > -1 ||
  //       // dependencyTitle.indexOf(dependencyTitle1) > -1

  //     })
  //     this.setState({
  //       dataSource: newData,
  //       text: text
  //     })
  //   }
  //   catch (error) {
  //     this.refs.toast.showBottom('No Results Found');
  //   }
  // }

  //to filter the search in put by user 
  SearchFilterFunction(text) {
    log("Info", "UserApprovedProjects:SearchFilterFunction(text) method is used for search functionality");
    console.log(text);
    const newData = this.arrayholder.filter(function (item) {
      const story_id = item.story_id.toUpperCase()
      const story_id1 = text.toUpperCase()
      const assigned_date = item.assigned_date.toUpperCase()
      const assigned_date1 = text.toUpperCase()
      const target_date = item.target_date.toUpperCase()
      const target_date1 = text.toUpperCase()
      const story_desc = item.story_desc.toUpperCase()
      const story_desc1 = text.toUpperCase()
      const assignedto = item.assignedto.toUpperCase()
      const assignedto1 = text.toUpperCase()
      //   const created_on = item.created_on.toUpperCase()
      //   const created_on1 = text.toUpperCase()



      return story_id.indexOf(story_id1) > -1 ||
        assigned_date.indexOf(assigned_date1) > -1 ||
        target_date.indexOf(target_date1) > -1 ||
        story_desc.indexOf(story_desc1) > -1 ||
        assignedto.indexOf(assignedto1) > -1


    })
    this.setState({
      dataSource: newData,
      text: text
    })
  }

  render() {
    if (this.state.isLoading) {
      return (
        <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
          <DotIndicator color='#00A2C1' />
        </View>
      );

    }
    return (
      <View style={styles.MainContainer}>


        <Item>
          <NavigationEvents
            onDidFocus={() => this.onRefresh()}
          />
          <Input placeholder="Search"
            onChangeText={(text) => this.SearchFilterFunction(text)} />
          <Icon style={{ marginRight: 10, color: 'black' }} size={20} name="search" />
        </Item>
        <Toast ref="toast" />
        <View style={{ height: '80%' }}>

        {/* <View style={{ flexDirection: 'row' }}>
              <Text style={{ marginTop: 5, color: 'blue', width: '60%', marginLeft: 5, fontSize: 14,fontWeight:'bold' }}>ACTIVE SPRINT - {(this.state.cropcode).substring(0, 3).toUpperCase()} : {this.state.moduleDesc}</Text>
              {this.state.sprint_status === 'commited' &&
                <Text style={{ width: 80,  color: 'orange',paddingTop:5,fontWeight:'bold' }}>Committed</Text>
              }
            </View> */}
      

          <FlatList

            extraData={this.state}
            keyExtractor={this._keyExtractor}
            renderItem={this._renderItem}
            style={{ flex: 1, }}
            data={this.state.dataSource}
            onRefresh={() => this.onRefresh()}
            refreshing={this.state.isFetching}

            ItemSeparatorComponent={this.FlatListItemSeparator}
            renderItem={({ item, index }) =>
              // <View style={[item.timeLeft<0?styles.container1:styles.container]} >
              <View>
                <ListItem navigation={this.props.navigation}
                  usertype={this.state.usertype}
                  empId={this.state.empId}
                  cropcode={this.state.cropcode}
                  Module={() => this.Module(item, index)}
                  item={item}
                  openModal={() => this.openModal(item, index)}
                  RoadBlock={() => this.RoadBlock(item, index)}//For Roadblock
                  Comments={() => this.Comments(item, index)}//For Comments
                  TaskChat={() => this.TaskChat(item, index)}//For TaskLevel Chat
                />
              </View>
            }
            keyExtractor={item => item.id}
            ListEmptyComponent={this._listEmptyComponent}
          />
        </View>

        <Modal

          offset={this.state.offset}
          closeOnTouchOutside={false}
          open={this.state.open}
          modalDidOpen={this.modalDidOpen}
          modalDidClose={this.modalDidClose}
          style={{ alignItems: "center", backgroundColor: 'white' }} >
          <View style={{ backgroundColor: 'white' }}>

            <View style={{ width: '100%', }}>

              <Text style={{ fontSize: 18, justifyContent: 'center', alignSelf: 'center', justifyContent: 'center' }}>Move To Inprogress</Text>
              {/* <Text style={{ marginLeft: 10, marginTop: 15, }}>Move To Inprogress</Text> */}
              <View style={{ flexDirection: 'row', paddingTop: 5 }}>

                <View style={{ paddingTop: 10, marginLeft: 15, }}>
                  <Text>Do you want to move Userstory into In Progress</Text>
                </View>
              </View>

            </View>

            <View style={{ justifyContent: 'flex-start', marginLeft: 15, }}>



            </View>

            <View style={{ flexDirection: 'row', marginTop: 10, justifyContent: "space-between" }}>
              <TouchableOpacity style={styles.opensave} onPress={this.updateActiveTaskStatus}>
                <Text style={{ color: 'white' }}>Yes</Text>

              </TouchableOpacity>
              <TouchableOpacity style={styles.opencancel} onPress={this.closeModal}>
                <Text style={{ color: 'white' }}>No</Text>
              </TouchableOpacity>

            </View>

          </View>

        </Modal>



      </View>
    );
  }
}

const styles = StyleSheet.create({
  MainContainer:
  {
    flex: 1,
    width: Dimensions.get('window').width,
    height: Dimensions.get('window').height,
  },
  container: {
    backgroundColor: '#ffcccc',
    paddingTop: 5,
    paddingRight: 20,
  },
  container1: {
    backgroundColor: '#ffffff',
    marginTop: 10,
    paddingRight: 20,
    margin: "2%",
    borderWidth: 0.8,
    borderColor: 'grey',
    width: '96%',
    borderRadius: 10
  },
  buttonContainer: {
    width: wp('100%'),
    alignSelf: 'baseline',
    color: '#d2691e',
    backgroundColor: '#fadbd8',
    marginLeft: wp('2%'),
    marginRight: wp('2%'),
  },
  signupButton: {
  },
  subcontainer: {
    flex: 2,
    flexDirection: 'row',
  },
  signUpText0: {
    fontSize: 14,
    color: 'green',
    paddingLeft: 10,
    //fontWeight: "bold",
  },
  signUpText1: {
    fontSize: 14,
    color: 'green',
    // fontWeight: "bold",
  },

  signUpText00: {
    fontSize: 13,
    color: '#323233',
    paddingLeft: 10,

  },
  signUpText11: {
    fontSize: 13,
    // paddingBottom: 10,
    color: '#000000',
    //fontWeight: "bold",
    width: wp('55%')

  },
  signUpText000: {
    fontSize: 12,
    color: 'black',
    // paddingBottom: 10,
    paddingLeft: 10,
  },
  signUpText111: {
    fontSize: 12,
    // paddingBottom: 10,

    color: 'black',

    paddingLeft: -20,
    width: '60%'
  },
  signUpText11111: {
    fontSize: 12,
    // paddingBottom: 10,

    color: 'black',

    paddingLeft: -20,
    // width: '60%'
  },
  signUpText1101: {
    fontSize: 12,
    // paddingBottom: 10,

    color: 'black',

    paddingLeft: -20,
    width: '70%'
  },
  end: {
    alignItems: 'flex-end',
  },
  end1: {
    flex: 1,
    justifyContent: 'space-between',
    flexDirection: 'row',
  },
  s: {
    justifyContent: 'center',

    backgroundColor: '#ed7070',
    shadowOffset: { width: 50, height: 50 },
    alignItems: 'center',
    width: wp('40%'),
    height: hp('12%'),
    borderTopLeftRadius: 10,
    borderBottomLeftRadius: 10,

  },
  signUpText2: {
    fontSize: 13,
    paddingRight: 10,
    paddingLeft: 13,
    color: 'black',
    justifyContent: 'center',

  },
  signUpText02: {
    fontSize: 13,
    paddingRight: 5,
    color: 'red',
    paddingLeft: 13,

    // paddingBottom: 10,
    // fontWeight: 'bold',
  },
  signUpText022: {
    fontSize: 13,
    paddingLeft: 13,
    color: 'green',
    // paddingBottom: 10,
    justifyContent: 'center',

  },
  signUpText002: {
    fontSize: 13,
    paddingLeft: 12,
    // paddingBottom: 10,
    color: 'black'

  },
  signUpText0002: {
    fontSize: 13,
    paddingRight: 45,
    // paddingTop: 20,
    paddingLeft: 13,
    // color: 'red',
    // paddingBottom: 10,
    // fontWeight: 'bold',
    justifyContent: 'center',

  },
  signUpText3: {

    // paddingBottom: 10,
    // paddingLeft: 10,
    fontSize: 13,
    // paddingRight:hp('-10%'),
    paddingRight: 13,
    width: '70%',
    // fontWeight: "bold",
    alignItems: 'center',
    color: '#000000'
  },
  signUpText4: {
    // paddingBottom: 10,
    paddingLeft: 10,
    // fontWeight: 'bold',
    color: '#323233',
    fontSize: 13,
    alignItems: 'center',
  },


  signUpText33: {

    // paddingBottom: 10,
    // paddingLeft: 13,
    fontSize: 13,
    // paddingRight:hp('-10%'),
    paddingRight: 35,
    // fontWeight: 'bold',
    // paddingTop: -10,
    alignItems: 'center',
    // width: wp('80%'),
    color: 'black'

  },
  signUpText44: {
    // paddingBottom: 10,
    paddingLeft: 10,
    // fontWeight: 'bold',
    paddingTop: -10,
    //color: 'black',
    fontSize: 13,
    alignItems: 'center',
    color: 'black'
  },

  signup: {
    //paddingTop:20,
    color: "#FFF",
  },
  boxone: {
    flex: 1,
    marginTop: 5,

  },
  boxtwo: {
    flex: 1,

  },
  boxthree: {
    flex: 1,

  },
  box: {
    justifyContent: 'space-between',
    flexDirection: 'row',
    position: 'relative',
    // marginBottom: 10,

  },
  box1: {
    justifyContent: 'space-between',
    flexDirection: 'row',
    position: 'relative',
    // marginBottom: 10,
    paddingRight: 25,
  },
  signUpText: {
    fontSize: 20,
    justifyContent: 'center',


    color: 'white',
    alignSelf: 'center',
  },
  boxheader: {
    //  backgroundColor:'green',
    justifyContent: 'space-between',
    flexDirection: 'column',
    position: 'relative',
    //marginBottom: 15,

  },
  opencancel: {
    flex: 1,
    ...Platform.select({
      ios: {
        backgroundColor: 'red', margin: 20, height: 30, alignItems:
          "center", justifyContent: 'center'
      },
      android: {
        backgroundColor: 'red', margin: 20, height: 30, alignItems:
          "center", justifyContent: 'center'
      },
    }),
  },
  opensave: {
    flex: 1,
    ...Platform.select({
      ios: {
        backgroundColor: 'green', margin: 20, height: 30, alignItems:
          "center", justifyContent: 'center'
      },
      android: {
        backgroundColor: 'green', margin: 20, height: 30, alignItems:
          "center", justifyContent: 'center'
      },
    }),
  },

});