import * as React from "react";
import { INavProps, INavLink } from "office-ui-fabric-react/lib/Nav";
import "./SideBarlLeft.css";
import { NavLink } from "react-router-dom";
import { Icon } from "office-ui-fabric-react";
import { FormattedMessage } from "react-intl";
// import { ListRecordsCriteria, FieldQuery, Sorting } from "src/Models";

import * as classNames from "classnames";
import { CachingService } from "../Services";

// import { CachingService } from "src/Services";
export class SideBarLeft extends React.Component<any, any> {
  private sideNavRef: any = React.createRef<HTMLElement>();
  private _loggedInUser: any;

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

    let cachingService: CachingService = new CachingService();
    this._loggedInUser = cachingService.read("LoggedInUser");

    //debugger;
    this.state = {
      selectedNavKey: "#",
      groups: [],
      subLinks: new Array<any>()
    };
  }
  componentWillMount() {
    this.loadLinks();
  }
  componentDidMount() {
    document.addEventListener("mousedown", this.handleClickOutside.bind(this));
    window.addEventListener("resize", this.changePageDimenstions.bind(this));
  }

  componentWillUnmount() {
    document.removeEventListener(
      "mousedown",
      this.handleClickOutside.bind(this)
    );
    window.removeEventListener("resize", this.changePageDimenstions.bind(this));
  }

  handleClickOutside(e: any) {
    if (this.sideNavRef && this.sideNavRef.current) {
      if (
        !this.sideNavRef.current.contains(e.target) &&
        !e.target.classList.contains("menuExpand")
      ) {
        this.closeSubMenu();
      }
    }
  }

  changePageDimenstions(e: any) {
    if (this.props.pageContainerRef && this.props.pageContainerRef.current) {
      this.props.pageContainerRef.current.classList.remove("full-menu");
      this.props.pageContainerRef.current.classList.remove("show-mobile-menu");
      this.props.pageContainerRef.current.classList.remove("menu-hidden");
      this.closeSubMenu();
    }
  }

  public render(): JSX.Element {
    return (
      <div className={classNames("sideBarLinks")} ref={this.sideNavRef}>
        <div className="main-links">
          {/* <Nav
                  selectedKey={ this.state.selectedNavKey }
                  groups={ this.state.groups }
                  expandedStateText={'expanded'}
                  collapsedStateText={'collapsed'}
                  onRenderLink={this._onRenderLink}
                  className="custom-sideNav"
                /> */}

          {!this.state.groups[0].links ? (
            ""
          ) : (
              <nav className="main-nav">
                {this.state.groups[0].links.map((link: any, index: any) => {
                  return link.isExpanded ? (
                    <a
                      className="main-link"
                      onClick={this._renderSubNav.bind(this, link.links)}
                      key={index}
                    >
                      <Icon
                        iconName={link.iconProps.className}
                        className={"nav-main-icon " + link.iconProps.className}
                      />
                      <span className="main-link-text">
                        <FormattedMessage id={link.name} />
                      </span>
                    </a>
                  ) : (
                      <NavLink
                        className="main-link"
                        to={link.url}
                        key={index}
                        onClick={this.closeSubMenu.bind(this)}
                      >
                        <Icon
                          iconName={link.iconProps.className}
                          className={"nav-main-icon " + link.iconProps.className}
                        />
                        <span className="main-link-text">
                          <FormattedMessage id={link.name} />
                        </span>
                      </NavLink>
                    );
                })}
              </nav>
            )}
        </div>
        <div className="sub-nav-menu">
          {this.state.subLinks
            ? this.state.subLinks.map((link: any, index: any) => {
              return (
                <NavLink
                  className="nav-sub-link"
                  to={link.url}
                  key={index}
                  onClick={link.onClick}
                >
                  <Icon
                    iconName={link.iconProps.className}
                    className={"nav-sub-icon " + link.iconProps.className}
                  />
                  <span className="nav-sub-text">
                    <FormattedMessage id={link.name} />
                  </span>
                </NavLink>
              );
            })
            : ""}
        </div>
      </div>
    );
  }
  private _renderSubNav(items: any) {
    if (items == this.state.subLinks) {
      this.closeSubMenu();
    } else {
      this.setState({ subLinks: items });
      this.props.pageContainerRef.current.classList.add("full-menu");
    }
  }

  private closeSubMenu() {
    this.setState({ subLinks: [] });
    this.props.pageContainerRef.current.classList.remove("full-menu");
    this.props.pageContainerRef.current.classList.remove("show-mobile-menu");
  }
  //  private linkClicked(params: any, screenIconClassName: string, screenTitle: string, url: string) {

  //       let cachingService: CachingService = new CachingService();
  //       cachingService.store("Params", params);
  //       cachingService.store("screenIconClassName", screenIconClassName);
  //       cachingService.store("screenTitle", screenTitle);
  //       // this.props.history.replace(url);
  //   }
  // private _onRenderLink = (link: any): JSX.Element | null => {
  //     return (
  //         <FormattedMessage id={link.name}/>
  //     );
  //   };

  private linkClicked(
    params: any,
    screenIconClassName: string,
    screenTitle: string,
    url: string
  ) {
    // let cachingService: CachingService = new CachingService();
    // cachingService.store("Params", params);
    // cachingService.store("screenIconClassName", screenIconClassName);
    // cachingService.store("screenTitle", screenTitle);
    this.closeSubMenu();
    // this.props.history.replace(url);
  }

  private loadLinks() {



    // let outgoingCriteria = new ListRecordsCriteria();
    // outgoingCriteria.asLookup = false;
    // outgoingCriteria.entityId = 14;
    // outgoingCriteria.query = new Array<FieldQuery>();
    // let outgoingFieldQuery = new FieldQuery();
    // outgoingFieldQuery.fieldId = 156;
    // outgoingFieldQuery.value = "11";
    // outgoingCriteria.sorting = new Sorting();
    // outgoingCriteria.sorting.fieldId = 190;
    // outgoingCriteria.sorting.direction = 1;
    // outgoingCriteria.query.push(outgoingFieldQuery);
    // let notDraftFieldQuery = new FieldQuery();
    // notDraftFieldQuery.fieldId = 176;
    // notDraftFieldQuery.value = "22";
    // notDraftFieldQuery.queryOperator = 1;
    // outgoingCriteria.query.push(notDraftFieldQuery);

    let links: INavLink[] = new Array<INavLink>();

    if (true) {
      let link = {
        iconProps: { className: "fal fa-home" },
        selectedKey: "dashboard",
        name: "Dashboard",
        url: "/",
        key: "dashboard"
      };

      links.push(link);
    }

    if (true) {
      let link: any = {
        links: [
          {
            iconProps: { className: "fal fa-plus" },
            selectedKey: "recordWizard",
            url: "/createCorrespondence",
            name: "Create",
            key: "recordWizard",
            onClick: this.linkClicked.bind(
              this,
              null,
              "fal fa-hdd",
              "Correspondences",
              "/recordsList"
            )
          },
          {
            iconProps: { className: "fal fa-inbox-out" },
            selectedKey: "outgoing",
            url: "/outgoing",
            name: "Outgoing",
            key: "Outgoing",
            forceAnchor: true,
            onClick: this.linkClicked.bind(
              this,
              null,
              "fal fa-hdd",
              "Correspondences",
              "/recordsList"
            )
          },
          {
            iconProps: { className: "fal fa-inbox-in" },
            selectedKey: "incoming",
            url: "/incoming",
            name: "Incoming",
            key: "Incoming",
            forceAnchor: true,
            onClick: this.linkClicked.bind(
              this,
              null,
              "fal fa-hdd",
              "Correspondences",
              "/recordsList"
            )
          },
          {
            iconProps: { className: "fal fa-inbox-out" },
            selectedKey: "drafts",
            url: "/drafts",
            name: "Drafts",
            key: "drafts",
            forceAnchor: true,
            onClick: this.linkClicked.bind(
              this,
              null,
              "fal fa-hdd",
              "Correspondences",
              "/recordsList"
            )
          },
          {
            iconProps: { className: "fal fa-inbox-out" },
            selectedKey: "Urgent",
            url: "/urgent",
            name: "Urgent",
            key: "Urgent",
            forceAnchor: true,
            onClick: this.linkClicked.bind(
              this,
              null,
              "fal fa-hdd",
              "Correspondences",
              "/recordsList"
            )
          },
          {
            iconProps: { className: "fal fa-inbox-out" },
            selectedKey: "Late",
            url: "/late",
            name: "Late",
            key: "Late",
            forceAnchor: true,
            onClick: this.linkClicked.bind(
              this,
              null,
              "fal fa-hdd",
              "Correspondences",
              "/recordsList"
            )
          }
          // { iconProps: { className: 'iconsmind-Speach-BubbleDialog' }, url:"/groupedList", name: "Conversations", key: 'conversations', forceAnchor: true,
          // onClick: this.linkClicked.bind(this, draftsCriteria, 'iconsmind-Speach-BubbleDialog', 'Conversations','/groupedList') }
        ],

        name: "Correspondences",
        isExpanded: true,
        iconProps: { className: "fal fa-inbox" }
      };

      //this.setState({groups:this.state.groups});

      links.push(link);


    }

    if (true) {
      let link: any = {
        links: [
          {
            iconProps: { className: "fal fa-plus" },
            selectedKey: "recordWizard",
            url: "/createTask",
            name: "Create",
            key: "recordWizard",
            onClick: this.linkClicked.bind(
              this,
              null,
              "fal fa-hdd",
              "Correspondences",
              "/recordsList"
            )
          },
          {
            iconProps: { className: "fal fa-tasks" },
            selectedKey: "tasks",
            url: "/tasks",
            name: "Tasks",
            key: "tasks",
            forceAnchor: true,
            onClick: this.linkClicked.bind(
              this,
              null,
              "fal fa-hdd",
              "Correspondences",
              "/recordsList"
            )
          },
        ],

        name: "Tasks",
        isExpanded: true,
        iconProps: { className: "fal fa-tasks" }
      };

      //this.setState({groups:this.state.groups});

      links.push(link);


    }

    if (true) {
      let link: any = {
        links: [
          {
            iconProps: { className: "fal fa-calendar-edit" },
            selectedKey: "createMeetingTemplate",
            url: "/createMeetingTemplate",
            name: "CreateMeetingTemplate",
            key: "createMeetingTemplate"
          },
          {
            iconProps: { className: "fal fa-calendar-edit" },
            selectedKey: "Meeting Templates",
            url: "/meetingTemplates",
            name: "MeetingTemplates",
            key: "Meeting Templates",
            forceAnchor: true
          },
          {
            iconProps: { className: "fal fa-calendar-alt" },
            selectedKey: "Meetings",
            url: "/meetings",
            name: "Meetings",
            key: "Meetings",
            forceAnchor: true
          },
          {
            iconProps: { className: "fal fa-location" },
            selectedKey: "createMeetingRoom",
            url: "/createMeetingRoom",
            name: "Add Meeting Room",
            key: "createMeetingRoom",
            forceAnchor: true
          },
          {
            iconProps: { className: "fal fa-location" },
            selectedKey: "MeetingRooms",
            url: "/meetingRooms",
            name: "Meeting Rooms",
            key: "MeetingRooms",
            forceAnchor: true
          },
        ],

        name: "Meetings",
        isExpanded: true,
        iconProps: { className: "fal fa-calendar-alt" }
      };

      //this.setState({groups:this.state.groups});

      links.push(link);


    }

    let hasAdminSecurityGroup;
    if (this._loggedInUser && this._loggedInUser.securityGroups) {
      this._loggedInUser.securityGroups.forEach((sg: any) => {
        if (sg.id == 1)
          hasAdminSecurityGroup = true;
      });
    }


    if (hasAdminSecurityGroup == true) {
      let link = {
        iconProps: { className: "fal fa-hdd" },
        selectedKey: "documents",
        name: "Documents",
        url: "/drive/1",
        key: "documents",
        onClick: this.linkClicked.bind(
          this,
          null,
          "fal fa-hdd",
          "Correspondences",
          "/recordsList"
        )
      };

      links.push(link);




    }

    let link2: any = {
      links: [
        {
          iconProps: { className: "fal fa-sitemap" },
          selectedKey: "organizationalUnits",
          url: "/organizationalUnits",
          name: "Organization Units",
          key: "organizationalUnits",
          onClick: this.linkClicked.bind(
            this,
            null,
            "fal fa-hdd",
            "Correspondences",
            "/recordsList"
          )
        },
        {
          iconProps: { className: "fal fa-sitemap" },
          selectedKey: "positions",
          url: "/positions",
          name: "Positions",
          key: "positions",
          forceAnchor: true,
          onClick: this.linkClicked.bind(
            this,
            null,
            "fal fa-hdd",
            "Correspondences",
            "/recordsList"
          )
        },
        {
          iconProps: { className: "fal fa-shield-check" },
          selectedKey: "securityGroups",
          url: "/securityGroups",
          name: "Security Groups",
          key: "securityGroups",
          forceAnchor: true,
          onClick: this.linkClicked.bind(
            this,
            null,
            "fal fa-hdd",
            "Correspondences",
            "/recordsList"
          )
        },
        {
          iconProps: { className: "fal fa-user-alt" },
          selectedKey: "userAccounts",
          url: "/userAccounts",
          name: "User Accounts",
          key: "userAccounts",
          forceAnchor: true,
          onClick: this.linkClicked.bind(
            this,
            null,
            "fal fa-hdd",
            "Correspondences",
            "/recordsList"
          )
        }
      ],

      name: "Users Management",
      isExpanded: true,
      iconProps: { className: "fal fa-users" }
    };


    links.push(link2);

    // if(true){
    //     let link:INavLink = { name: 'Documents', url: '/drive', key: 'drives',isExpanded: true};

    //     this._fileService.listDrives()
    //     .then((result)=>{
    //         link.links = new Array<INavLink>();
    //         for (let drive of result) {
    //             link.links.push({ name: drive.name, url: '/drive/' + drive.id, key: 'drive'+drive.id });

    //         }
    //         this.setState({groups:this.state.groups});
    //     });

    //     links.push(link);
    // }

    this.state.groups.push({ links });
    this.state.groups.push({ links });
    this.setState({ groups: this.state.groups });
  }
}
