var FILTER_DRAWER = {};

window.FilterWrapper = React.createClass({
  getInitialState: function(){
    return{
      filterKey: this.props.filterKey,
      data: null,
      openDrawer: false
    }
  },
  getData: function(){
    var capture = this;
    var agencyId = $("#agency-select").val();
    //console.log(agencyId);
    $.post("AdminAjaxHandler.ashx?handler=GetFilterJSON", {filterKey: this.state.filterKey, agencyId: agencyId}, function (data) {
      var parsed = JSON.parse(data);
      //console.log("Initial Data:", parsed);
      capture.setState({
          data: parsed,
          isUpdating: false
      }, function () {});
      //var json = JSON.stringify(parsed);
      //$.post("AdminAjaxHandler.ashx?handler=SaveFilterJSON", { filters: json, filterKey: parsed.filterKey }, function (data2) {
      //    window.refreshGrid(parsed.filterKey, true);
      //});
    });
  },
  componentDidMount: function(){
    //console.log("ComponentDidMount");
    this.getData();
  },
  componentWillMount: function(){
    var capture = this;
    FILTER_DRAWER.updateSingleTree = this.updateSingleTree;
    FILTER_DRAWER.updateDoubleTreeL1 = this.updateDoubleTreeL1;
    FILTER_DRAWER.updateDoubleTreeL2 = this.updateDoubleTreeL2;
    window.openDrawer = function(key){
      capture.setState({
        filterKey: key
      }, function(){
        capture.getData();
        capture.openDrawer();
      })
    }
  },
  openDrawer: function(){
    if(this.state.openDrawer){
      this.setState({
        openDrawer: false
      })
    }else{
      this.setState({
        openDrawer: true
      })
    }
  },
  closeDrawer: function(){
    this.setState({
      openDrawer: false
    })
  },
  updateSingleTree: function(filterId, id, value){
    //console.log("I got the data: ", filterId, id, value);
    var data = this.state.data;
    var newData = data.filters.filter(function(topFilter){
      if(topFilter.id == filterId){
        var checks = topFilter.data.filter(function(check){
          if(check.id == id){
            check.checked_yn = value;
          }
          return check;
        })
        topFilter.data = checks;
      }
      return topFilter;
    })
    data.filters = newData;
    this.setState({
      data: data
    })
  },
  updateDoubleTreeL1: function(filterId, id, value){
    //console.log("I got the data: ", filterId, id, value);
    var data = this.state.data;
    var newData = data.filters.filter(function(topFilter){
      if(topFilter.id == filterId){
        var checks = topFilter.data.filter(function(check){
          if(check.id == id){
            check.checked_yn = value;
            var checks2 = check.data.filter(function(check2){
              check2.checked_yn = value;
              return check2;
            })
            check.data = checks2;
          }
          return check;
        })
        topFilter.data = checks;
      }
      return topFilter;
    })
    data.filters = newData;
    this.setState({
      data: data
    })
  },
  updateDoubleTreeL2: function(filterId, l1id, l2id, value){
    //console.log("I got the data: ", filterId, l1id, l2id, value);
    var data = this.state.data;
    var newData = data.filters.filter(function(topFilter){
      if(topFilter.id == filterId){
        var checks = topFilter.data.filter(function(check){
          if(check.id == l1id){
            check.checked_yn = value;
            var checks2 = check.data.filter(function(check2){
              if(check2.id == l2id){
                check2.checked_yn = value;
              }
              return check2;
            })
            check.data = checks2;
          }
          return check;
        })
        topFilter.data = checks;
      }
      return topFilter;
    })
    data.filters = newData;
    //console.log(data.filters);
    this.setState({
      data: data
    })
  },
  render: function(){
    return(
      <div className="filter-parent">
        {
          this.state.data != null && this.state.openDrawer ?
          <FilterDrawer filterKey={this.state.filterKey} data={this.state.data} closeDrawer={this.closeDrawer} isUpdating={this.state.isUpdating}/>
          :
          null
        }
      </div>
    )
  }
})

var FilterDrawer = React.createClass({
  getInitialState: function(){
    return{
      currentFilter: "main",
      data: null,
      filterId: null,
      drawerAnimation: "slideInRight fast-animation",
      shadeAnimation: "fadeIn fast-animation"
    }
  },
  componentWillMount: function(){
    this.setState({
      data: this.props.data
    })
  },
  loadFilterByControlType: function(){
    switch (this.state.currentFilter){
      case "main":
      if(!this.props.isUpdating){
        return (<Main data={this.props.data} changeCurrentFilter={this.changeCurrentFilter}/>);
      }else{
        return(<div className="filter-div-reset filter-loading-bar filter-preloader">
        </div>)
      }
        break;
      case "singleTree":
        return (<SingleTree filterId={this.state.filterId} data={this.state.data} />);
        break;
      case "doubleTree":
        return (<DoubleTree filterId={this.state.filterId} data={this.state.data} />);
        break;
    }
  },
  changeCurrentFilter: function(id, type, data){
    this.setState({
      currentFilter: type,
      data: data,
      filterId: id
    })
  },
  loadMain: function(){
    this.setState({
        currentFilter: "main",
        data: this.props.data,
        id: null
    })
  },
  closeDrawer: function(){
    var capture = this;
    this.setState({
      drawerAnimation: "slideOutRight fast-animation",
      shadeAnimation: "fadeOut fast-animation"
    }, function(){
      $(".filter-drawer").one('webkitAnimationEnd oanimationend msAnimationEnd animationend',
        function(e) {
          capture.props.closeDrawer();
      });
    })
  },
  saveAndClose: function(){
    var capture = this;
    var json = JSON.stringify(this.props.data);
    $.post("AdminAjaxHandler.ashx?handler=SaveFilterJSON", {filters: json, filterKey: this.props.filterKey}, function (data) {
      window.refreshGrid(capture.props.filterKey, true);
    });
    this.closeDrawer();
  },
  clearFilters: function(){
    var capture = this;
    $.post("AdminAjaxHandler.ashx?handler=SaveFilterJSON", {filters: null, filterKey: this.props.filterKey}, function (data) {
      window.refreshGrid(capture.props.filterKey, true);
    });
    this.closeDrawer();
  },
  render: function(){
    //console.log("Render", this.props.data);
    return(
      <div className="filter-drawer-container">
          <div className={"filter-drawer animated " + this.state.drawerAnimation}>
            <h2 className="filter-header">
              <span className={this.state.currentFilter == 'main' ? "glyphicon glyphicon-filter filter-header-icon" : "glyphicon glyphicon-chevron-left filter-header-icon"} onClick={this.loadMain}></span>
              <span className="filter-header-title" onClick={this.loadMain}><b>Filter</b> Packets</span>
              <div className="filter-exit-button filter-button filter-button-secondary pull-right" onClick={this.closeDrawer}><i className="fa fa-times"></i></div>
              <div className="filter-button filter-button-secondary pull-right" onClick={this.clearFilters}>Clear</div>
              <div className="filter-button filter-button-primary pull-right" onClick={this.saveAndClose}>Apply</div>
            </h2>
            {!this.props.isUpdating ?
              this.loadFilterByControlType()
              :
              <div className="filter-div-reset filter-loading-bar filter-preloader">

              </div>
            }
          </div>
        <div className={"filter-drawer-shade " + this.state.shadeAnimation}></div>
      </div>
    )
  }
})

var Main = React.createClass({
  changeCurrentFilter: function(id, type, data){
    this.props.changeCurrentFilter(id, type, data);
  },
  render: function(){
    var capture = this;
    return (
      <div className="filter-div-reset">
        {
          this.props.data.filters.map(function(filter, i){
            //console.log(filter.name);
            return (<Filter filterId={filter.id} name={filter.name} data={filter.data} controlType={filter.controlType} key={i} changeCurrentFilter={capture.changeCurrentFilter}/>);
          })
        }
      </div>
    )
  }
})

var Filter = React.createClass({
  changeCurrentFilter: function(){
    this.props.changeCurrentFilter(this.props.filterId, this.props.controlType, this.props.data);
  },
  render: function(){
    return (
      <div className="row filter-container filter-div-reset" onClick={this.changeCurrentFilter}>
        <div className="col-xs-12 filter-div-reset">
          <h4 className="filter-title">{this.props.name}</h4>
          <span className="glyphicon glyphicon-chevron-right pull-right filter-pull-icon"></span>
        </div>
      </div>
    )
  }
})

var SingleTree = React.createClass({
  render: function(){
    var capture = this;
    return(
      <div className="filter-div-reset">
        {
          this.props.data.map(function(check, i){
            return (<CheckSingle filterId={capture.props.filterId} id={check.id} name={check.name} checked_yn={check.checked_yn} key={i} />);
          })
        }
      </div>
    )
  }
})

var DoubleTree = React.createClass({
  render: function(){
    var capture = this;
    return(
      <div className="filter-div-reset">
        {
          this.props.data.map(function(check, i){
            return (<CheckLevel1 filterId={capture.props.filterId} id={check.id} name={check.name} checked_yn={check.checked_yn} data={check.data} key={i} />);
          })
        }
      </div>
    )
  }
})

var CheckSingle = React.createClass({
  getCheckedClass: function(){
    if(this.props.checked_yn){
      return "filter-checkbox-label-checked";
    }else{
      return "";
    }
  },
  updateSingleTree: function(){
    FILTER_DRAWER.updateSingleTree(this.props.filterId, this.props.id, !this.props.checked_yn);
  },
  render: function(){
    return(
      <div className="row filter-list-item-container filter-div-reset" >
        <div className="col-xs-12 filter-div-reset" >
        <label className={"filter-checkbox-label " + this.getCheckedClass()}>
          <input type="checkbox"  onClick={this.updateSingleTree} id={"filter-checkbox-" + this.props.name} name={"filter-checkbox-"} readOnly={true} checked={this.props.checked_yn} className="filter-checkbox" />
        </label>
          <h4 className="filter-list-item-title">{this.props.name}</h4>
        </div>
      </div>
    )
  }
})

var CheckLevel1 = React.createClass({
  getInitialState: function(){
    return {
      expanded: false,
      iconClass: " glyphicon-chevron-down "
    }
  },
  getCheckedClass: function(){
    var hasPrograms = false;
    var numPrograms = this.props.data.length;
    var numChecked = 0;
    this.props.data.filter(function(check){
      if(check.checked_yn){
        hasPrograms = true;
        numChecked ++;
      }
    })
    var allChecked = numPrograms == numChecked;

    if(this.props.checked_yn){
      if(hasPrograms){
        if(allChecked){
          return "filter-checkbox-label-checked";
        }else{
          return "filter-checkbox-label-checked-some";
        }
      }else{
        return "filter-checkbox-label-checked";
      }
    }else{
      if(hasPrograms){
        if(allChecked){
          return "filter-checkbox-label-checked";
        }else{
          return "filter-checkbox-label-checked-some";
        }
      }else{
        return "";
      }
    }
  },
  expandDrawer: function(){
    if(this.state.expanded){
      this.setState({
        expanded: false,
        iconClass: " glyphicon-chevron-down "
      })
    }else{
      this.setState({
        expanded: true,
        iconClass: " glyphicon-chevron-up "
      })
    }
  },
  updateDoubleTree: function(){
    FILTER_DRAWER.updateDoubleTreeL1(this.props.filterId, this.props.id, !this.props.checked_yn);
  },
  render: function(){
    var capture = this;
    return(
      <div className="filter-tree-container">
        <div className="row filter-list-item-container filter-div-reset" onClick={this.expandDrawer}>
          <div className="col-xs-12 filter-div-reset" >
          <label className={"filter-checkbox-label " + this.getCheckedClass()}>
            <input type="checkbox"  onClick={this.updateDoubleTree} id={"filter-checkbox-" + this.props.name} name={"filter-checkbox-"} readOnly={true} checked={this.props.checked_yn} className="filter-checkbox" />
          </label>
            <h4 className="filter-list-item-title">{this.props.name}
              <span className={"glyphicon " + this.state.iconClass + " pull-right filter-drop-icon"}></span>
            </h4>
          </div>
        </div>
        {capture.state.expanded ?
        <div className="filter-program-drawer ">
          {
            this.props.data.map(function(check, i){
              return <CheckLevel2 name={check.name} key={i} filterId={capture.props.filterId} l1id={capture.props.id} updateFilter={capture.updateFilter} id={check.id} checked_yn={check.checked_yn}/>
            })
          }
        </div>
        :
        null
        }
      </div>
    )
  }
})

var CheckLevel2 = React.createClass({
  getCheckedClass: function(){
    if(this.props.checked_yn){
      return "filter-checkbox-label-checked";
    }else{
      return "";
    }
  },
  updateSingleTree: function(){
    FILTER_DRAWER.updateDoubleTreeL2(this.props.filterId, this.props.l1id, this.props.id, !this.props.checked_yn);
  },
  render: function(){
    return(
      <div className="row filter-list-item-container-level-2 filter-div-reset filter-check-level-2" >
        <div className="col-xs-12 filter-div-reset" >
        <label className={"filter-checkbox-label " + this.getCheckedClass()}>
          <input type="checkbox"  onClick={this.updateSingleTree} id={"filter-checkbox-" + this.props.name} name={"filter-checkbox-"} readOnly={true} checked={this.props.checked_yn} className="filter-checkbox" />
        </label>
          <h4 className="filter-list-item-title">{this.props.name}</h4>
        </div>
      </div>
    )
  }
})
