import * as React from "react";
import { UserService, CachingService } from "../Services";
import { User } from "../Models";
import { NormalPeoplePicker, IPersonaProps, IBasePickerSuggestionsProps, IBasePicker, ValidationState } from "office-ui-fabric-react";
import Label from "reactstrap/lib/Label";
import "./UsersDropdown.css";

export class UsersDropdown extends React.Component<any, any> {
  private _userService: UserService = new UserService();
  private _picker = React.createRef<IBasePicker<IPersonaProps>>();
  private _cachingService = new CachingService();

  private suggestionProps: IBasePickerSuggestionsProps = {
    suggestionsHeaderText: this._cachingService.readPersistant("Language") == 0 ? 'Suggested People' : 'الأشخاص المقترحون',
    mostRecentlyUsedHeaderText: this._cachingService.readPersistant("Language") == 0 ? 'Suggested Contacts' : 'الأشخاص المقترحون',
    noResultsFoundText: this._cachingService.readPersistant("Language") == 0 ? 'No results found' : 'لم يتم العثور على نتائج',
    loadingText: this._cachingService.readPersistant("Language") == 0 ? 'Loading' : 'جاري العمل',
    showRemoveButtons: true,
    suggestionsAvailableAlertText: this._cachingService.readPersistant("Language") == 0 ? 'Suggested contacts' : 'الأشخاص المقترحون',
    suggestionsContainerAriaLabel: this._cachingService.readPersistant("Language") == 0 ? 'Suggested contacts' : 'الأشخاص المقترحون'
  };

  constructor(props: any) {
    super(props);

    this.state = {
      users: new Array<User>(),
      peopleList: [],
      mostRecentlyUsed: [],
      currentSelectedItems: [],
      getUsersCondition: null
    };

    this._loadUsers();
  }

  private _loadUsers() {
    debugger;
    if (this.props.getUsersCondition && this.props.getUsersCondition.organizationUnit)
      this._userService.listOrganizationUsers(this.props.getUsersCondition.organizationUnit).then((users: any[]) => {
        console.log(users)

        let usersList: IPersonaProps[] = users.map(x => {
          //debugger;
          return { text: x.name, secondaryText: x.positions, id: x.id, key: x.id }
        });

        this.setState({ peopleList: usersList })
      });
    else
      this._userService.listUsers().then((users: any[]) => {
        console.log(users)

        let usersList: IPersonaProps[] = users.map(x => {
          //debugger;
          return { text: x.name, secondaryText: x.positions, id: x.id, key: x.id }
        });;


        this.setState({ peopleList: usersList })
      });
  }


  private _onFilterChanged = (
    filterText: string,
    currentPersonas: IPersonaProps[],
    limitResults?: number
  ): IPersonaProps[] | Promise<IPersonaProps[]> => {
    if (filterText) {
      let filteredPersonas: IPersonaProps[] = this._filterPersonasByText(filterText);

      filteredPersonas = this._removeDuplicates(filteredPersonas, currentPersonas);
      filteredPersonas = limitResults ? filteredPersonas.splice(0, limitResults) : filteredPersonas;
      return this._filterPromise(filteredPersonas);
    } else {
      return [];
    }
  };

  private _returnMostRecentlyUsed = (currentPersonas: IPersonaProps[]): IPersonaProps[] | Promise<IPersonaProps[]> => {
    //debugger;
    return this._filterPromise(this.state.peopleList)
  };

  private _getTextFromItem(persona: IPersonaProps): string {
    return persona.text as string;
  }

  private _onRemoveSuggestion = (item: IPersonaProps): void => {
    const { peopleList, mostRecentlyUsed: mruState } = this.state;
    const indexPeopleList: number = peopleList.indexOf(item);
    const indexMostRecentlyUsed: number = mruState.indexOf(item);

    if (indexPeopleList >= 0) {
      const newPeople: IPersonaProps[] = peopleList.slice(0, indexPeopleList).concat(peopleList.slice(indexPeopleList + 1));
      this.setState({ peopleList: newPeople });
    }

    if (indexMostRecentlyUsed >= 0) {
      const newSuggestedPeople: IPersonaProps[] = mruState
        .slice(0, indexMostRecentlyUsed)
        .concat(mruState.slice(indexMostRecentlyUsed + 1));
      this.setState({ mostRecentlyUsed: newSuggestedPeople });
    }
  };

  private _validateInput = (input: string): ValidationState => {
    if (input.indexOf('@') !== -1) {
      return ValidationState.valid;
    } else if (input.length > 1) {
      return ValidationState.warning;
    } else {
      return ValidationState.invalid;
    }
  };




  private _filterPersonasByText(filterText: string): IPersonaProps[] {
    return this.state.peopleList.filter((item: any) => this._doesTextStartWith(item.text as string, filterText));
  }

  private _removeDuplicates(personas: IPersonaProps[], possibleDupes: IPersonaProps[]) {
    return personas.filter(persona => !this._listContainsPersona(persona, possibleDupes));
  }

  private _filterPromise(personasToReturn: IPersonaProps[]): IPersonaProps[] | Promise<IPersonaProps[]> {
    if (this.state.delayResults) {
      return this._convertResultsToPromise(personasToReturn);
    } else {
      return personasToReturn;
    }
  }

  private _doesTextStartWith(text: string, filterText: string): boolean {
    return text.toLowerCase().indexOf(filterText.toLowerCase()) === 0;
  }


  private _listContainsPersona(persona: IPersonaProps, personas: IPersonaProps[]) {
    if (!personas || !personas.length || personas.length === 0) {
      return false;
    }
    return personas.filter(item => item.text === persona.text).length > 0;
  }

  private _convertResultsToPromise(results: IPersonaProps[]): Promise<IPersonaProps[]> {
    return new Promise<IPersonaProps[]>((resolve, reject) => setTimeout(() => resolve(results), 2000));
  }

  _onItemsChange(items: any[]) {
    debugger;
    let ids: any = [];

    items.forEach(el => {
      ids.push(el.id);
    });

    this.setState({
      currentSelectedItems: items,
      selectedIds: ids
    });

    this.props.onChanged(ids);
  };

  public render(): JSX.Element {

    if (this.state.getUsersCondition != this.props.getUsersCondition) {
      this._loadUsers();
      this.setState({ 'getUsersCondition': this.props.getUsersCondition })
    }

    return (
      <div>
        {/* 
                <Dropdown
                    {...this.props}
                    options={this.state.users.map((user: User) => { return { key: user.id, text: user.name } })}
                /> */}
        <Label className={this.props.required == true ? "ms-Label custom-label required" : "ms-Label custom-label"} >{this.props.label}</Label>

        <NormalPeoplePicker
          {...this.props}
          itemLimit={this.props.multiSelect == true ? undefined : 1}
          onResolveSuggestions={this._onFilterChanged.bind(this)}
          onEmptyInputFocus={this._returnMostRecentlyUsed.bind(this)}
          getTextFromItem={this._getTextFromItem.bind(this)}
          pickerSuggestionsProps={this.suggestionProps}
          className={this.props.errorMessage ? "ms-PeoplePicker errored" : "ms-PeoplePicker"}
          onRemoveSuggestion={this._onRemoveSuggestion.bind(this)}
          onValidateInput={this._validateInput.bind(this)}
          removeButtonAriaLabel={"Remove"}
          inputProps={{
            onBlur: (ev: React.FocusEvent<HTMLInputElement>) =>
              console.log("onBlur called"),
            onFocus: (ev: React.FocusEvent<HTMLInputElement>) =>
              console.log("onFocus called"),
            "aria-label": "People Picker"
          }}
          componentRef={this._picker}
          onChange={this._onItemsChange.bind(this)}
        //   disabled={this.state.isPickerDisabled}
        />

        {
          this.props.errorMessage ?
            <div className="custom-error-message">{this.props.errorMessage}</div> :
            ""
        }


      </div>
    );
  }
}
