import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';

import { BrandBar } from 'catalyst-ui';
import { mapStateToProps, mapDispatchToProps } from './propMaps.js';
import { navColToArray } from '../utils/NavigationCollection.js';
import ProfileViewModel from './ProfileViewModel.js';

/**
 * Brand Component wraps all of the peoplesoft components
 */
export class BrandBarProvider extends Component {

  constructor() {
    super(...arguments);

    this.getUpdateProfileLink = this.getUpdateProfileLink.bind(this);
    this.getPrivacySettingsLink = this.getPrivacySettingsLink.bind(this);

    this.getLauncherData = this.getLauncherData.bind(this);
    this.getLinksNavColData = this.getLinksNavColData.bind(this);

    this.onTouchTapNotifications = this.onTouchTapNotifications.bind(this);
    this.onTouchTapLauncher = this.onTouchTapLauncher.bind(this);
    this.onTouchTapProfile = this.onTouchTapProfile.bind(this);
  }

  /**
   * Stops notification updates/refreshes. Sets timer to zero to let users know
   * timer is not running.
   */
  componentWillUnmount() {
    clearInterval(this.timer);
    this.timer = 0;
  }

  onTouchTapNotifications() {
    this.fetchEvents();
  }

  onTouchTapLauncher() {
    this.fetchLauncher();
  }

  onTouchTapProfile() {
    this.fetchProfile();
  }

  /**
   * Starts refresh timer and loads store
   * @return {[type]} [description]
   */
  fetchEvents() {
    const dispatchers = this.props.storeDispatchers;
    const events = this.props.storeStates.events;

    if (!events || (!events.data && !events.isFetching)) {
      try {
        dispatchers.fetchEvents();
        this.timer = setInterval(dispatchers.fetchEvents, 2700000);
      } catch (e) {
        console.log(e);
      }
    }
  }

  fetchLauncher() {
    const dispatchers = this.props.storeDispatchers;
    const launcherData = this.props.storeStates.launcherData;

    if (!launcherData || (!launcherData.data && !launcherData.isFetching)
      || (launcherData.lastAction && launcherData.lastAction.status === 'error')
      || !launcherData.data[__LAUNCHER_PAGELET_NAME__]) {
      dispatchers.fetchLauncher();
    }
  }

  fetchProfile() {
    const {profileLinksData, profileData, pictureData} = this.props.storeStates;
    const dispatchers = this.props.storeDispatchers;

    if (!profileLinksData || (!profileLinksData.data && !profileLinksData.isFetching)
      || (profileLinksData.lastAction && profileLinksData.lastAction.status === 'error')
      || !profileLinksData.data[__PROFILE_LINKS_PAGELET_NAME__]) {
      dispatchers.fetchProfileLinks();
    }

    if (!profileData || (!profileData.data && !profileData.isFetching)
      || (profileData.lastAction && profileData.lastAction.status === 'error')) {
      dispatchers.fetchProfile();
    }
    if (!pictureData || (!pictureData.data && !pictureData.isFetching)
      || (pictureData.lastAction && pictureData.lastAction.status === 'error')) {
      dispatchers.fetchPicture();
    }
  }

  getLinksNavColData() {
    const data = this.props.storeStates.profileLinksData;

    if (!data
      || (data.lastAction && data.lastAction.status === 'error')
      || !data.data || !data.data[__PROFILE_LINKS_PAGELET_NAME__]) {
      return null;
    }

    return navColToArray(data.data[__PROFILE_LINKS_PAGELET_NAME__]);
  }


  /**
   * Returns link based on security role. Onestop > Radius > Catalyst
   * @return {string} absolute URL
   */
  getUpdateProfileLink() {
    const links = this.getLinksNavColData();

    if (!links) {
      return '';
    }

    // Onestop
    let link = links.find(item => item.TargetCRefName === 'UCI_ONESTOP_UPDATE_PROFILE');

    // Radius
    if (!link) {
      link = links.find(item => item.TargetCRefName === 'UCI_RADIUS_UPDATE_PROFILE');
    }

    // Catalyst
    if (!link) {
      link = links.find(item => item.TargetCRefName === 'UCI_UPDATE_PROFILE');
    }

    return link !== undefined ? link.AbsolutePortalURL : link;
  }

  getPrivacySettingsLink() {
    const links = this.getLinksNavColData();

    if (!links) {
      return '';
    }

    const link = links.find(item => item.TargetCRefName === 'UCI_PRIVACY_SETTINGS');
    return link !== undefined ? link.AbsolutePortalURL : link;
  }

  getLauncherData() {
    const launcherData = this.props.storeStates.launcherData;

    if (!launcherData
      || (launcherData.lastAction && launcherData.lastAction.status === 'error')
      || !launcherData.data || !launcherData.data[__LAUNCHER_PAGELET_NAME__]) {
      return null;
    }

    return launcherData.data[__LAUNCHER_PAGELET_NAME__];
  }

  render() {
    const states = this.props.storeStates;
    const dispatchers = this.props.storeDispatchers;

    const profileData = ProfileViewModel.toViewModel(
      states.profileData.data,
      states.pictureData.data
    );

    return (
      <BrandBar
        tabs={this.props.tabs}
        events={states.events.data}
        changeReadStatus={dispatchers.changeReadStatus}
        onTouchTapNotifications={this.onTouchTapNotifications}
        launcherData={this.getLauncherData()}
        onTouchTapLauncher={this.onTouchTapLauncher}
        profileData={profileData}
        onTouchTapProfile={this.onTouchTapProfile}
        updateProfileUrl= {this.getUpdateProfileLink()}
        privacySettingsUrl= {this.getPrivacySettingsLink()}
        logoutUrl={__LOGOUT_URL__}
        homeUrl={__HOME_URL__}
        lookupData={states.lookupData.data}
        fetchUCID={dispatchers.fetchUcidLookup}
        invalidateUCID={dispatchers.invalidateUcidLookup}
        hideUCIDLookup= {this.props.hideUCIDLookup}
        hideNotifications= {this.props.hideNotifications}
        hideLauncher= {this.props.hideLauncher}
        zDepth= {this.props.zDepth}
      />
    );
  }
}

BrandBarProvider.propTypes = {
  tabs: PropTypes.array,
  storeStates: PropTypes.object.isRequired,
  storeDispatchers: PropTypes.object.isRequired,
  hideUCIDLookup: PropTypes.bool,
  hideNotifications: PropTypes.bool,
  hideLauncher: PropTypes.bool,
  zDepth: PropTypes.number,
};

BrandBarProvider.childContextTypes = {
  muiTheme: PropTypes.object,
};

export default connect(mapStateToProps, mapDispatchToProps)(BrandBarProvider);
