import React from 'react';
import Loading from '../bricks/loading.js';
import Lsi from '../bricks/lsi.js';
import Error from '../bricks/error.js';
import Tools from './tools.js';
import Environment from '../environment/environment.js';

export const VucMixin = {

  //@@viewOn:mixins
  mixins: [],
  //@@viewOff:mixins

  //@@viewOn:statics
  statics: {
    layoutType: 'vuc',
    UU5_Common_VucMixin: {
      requiredMixins: ['UU5_Common_BaseMixin'],
      calls: {
        authorizeVuc: 'authorizeVuc'
      },
      errors: {
        sysAuthorizeVuc: 'Error of VUC %s during connection to server.',
        notErrorRoute: 'Error route was not set either in props or in Environment.',
        notCall: 'Call %s was not found either in props or in Environment.'
      },
      lsi: {
        notAuthorized: {
          cs: 'Nemáte práva na zobrazení vizuálního případu užití.',
          en: 'You have not permission to show visual use case.'
        },
        serverConnection: {
          cs: 'Server je dočasně nedostupný.',
          en: 'Server is temporarily unavailable.'
        }
      }
    }
  },
  //@@viewOff:statics

  //@@viewOn:propTypes
  propTypes: {
    authorized: React.PropTypes.bool,
    calls: React.PropTypes.object,
    errorRoute: React.PropTypes.oneOfType([
      React.PropTypes.string, // path
      React.PropTypes.element,
      React.PropTypes.shape({
        tag: React.PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.func]),
        props: React.PropTypes.object
      })
    ]),
    params: React.PropTypes.object
  },
  //@@viewOff:propTypes

  //@@viewOn:getDefaultProps
  getDefaultProps() {
    return {
      authorized: true,
      calls: null,
      errorRoute: null,
      params: null
    }
  },
  //@@viewOff:getDefaultProps

  //@@viewOn:standardComponentLifeCycle
  getInitialState() {
    // initialize
    this.registerMixin('UU5_Common_VucMixin');
    this.constructor.vucTitle && this.setTitle();

    return {
      authorizedFeedback: this.props.authorized ? 'loading' : 'ready',
      profiles: null
    };
  },

  componentDidMount() {
    $(window).on(Tools.events.lsi, this.setTitle);
    this.props.authorized && this._checkAuthorizing();
  },

  componentWillUnmount: function () {
    this._unmounted = true;
    $(window).off(Tools.events.lsi, this.setTitle);
  },
  //@@viewOff:standardComponentLifeCycle

  //@@viewOn:interface
  hasUU5_Common_VucMixin: function () {
    return this.hasMixin('UU5_Common_VucMixin');
  },

  getUU5_Common_VucMixinProps: function () {
    return {
      // profiles: this.props.profiles
    };
  },

  getUU5_Common_VucMixinPropsToPass: function () {
    return this.getUU5_Common_VucMixinProps();
  },
  getProfiles(){
    return this.state.profiles
  },

  isReady(){
    return this.state.authorizedFeedback == 'ready'
  },

  isLoading(){
    return this.state.authorizedFeedback == 'loading'
  },

  isError(){
    return this.state.authorizedFeedback == 'error'
  },

  getVucChildren(getChildren) {
    let result;

    switch (this.state.authorizedFeedback) {
      case 'loading':
        result = <Loading />;
        break;
      case 'ready':
        result = getChildren(this.state.profiles);
        break;
      case 'error':
        result = (
          <Error>
            <Lsi lsi={this.state.message} />
          </Error>
        );
        break;
    }

    return result;
  },

  checkAuthorizing() {
    this._checkAuthorizing();
    return this;
  },

  setTitle(title) {
    title = title || this.constructor.vucTitle;

    if (title) {
      if (typeof title === 'object') {
        title = this.getLSIItemByLanguage(title);
      }

      document.title = title;
    }

    return this;
  },
  //@@viewOff:interface

  //@@viewOn:overridingMethods
  //@@viewOff:overridingMethods

  //@@viewOn:componentSpecificHelpers
  _getAuthorizeVucCall() {
    let call;

    if (this.props.calls) {
      call = this.props.calls[this.getCallName('authorizeVuc', 'UU5_Common_VucMixin')];
    } else if (Environment.App && Environment.App.callConfig && Environment.App.callConfig.authorizeVuc) {
      call = Environment.App.callConfig.authorizeVuc
    }

    return call;
  },

  _checkAuthorizing() {
    let call = this._getAuthorizeVucCall();

    if (call) {
      // data = {}
      let data = { name: this.constructor.vucName };

      call({
        data: data,
        // dtoOut = {profiles: ['..', '..', ...], status: 'ok | error'}
        done: dtoOut => {
          if (!this._unmounted) {
            if (dtoOut.data.status === 'error') {
              let errorRoute = this.props.errorRoute;
              if (!errorRoute) {
                if (Environment.App && Environment.App.vucConfig && Environment.App.vucConfig.errorRoute) {
                  errorRoute = Environment.App.vucConfig.errorRoute;
                } else {
                  this.showError('notErrorRoute', null, {
                    mixinName: 'UU5_Common_VucMixin',
                    context: { environment: Environment }
                  });
                }
              }
              if (errorRoute) {
                this.setRoute(errorRoute);
              } else {
                this.setState({
                  authorizedFeedback: 'error',
                  message: this.getLSI('notAuthorized', 'UU5_Common_VucMixin')
                });
              }
            } else {
              this.setState({ authorizedFeedback: 'ready', profiles: dtoOut.data.profiles });
            }
          }
        },
        fail: dtoOut => {
          if (!this._unmounted) {
            this.showError('sysAuthorizeVuc', this.constructor.vucName || window.location.pathname, {
              mixinName: 'UU5_Common_VucMixin',
              context: { dtoOut: dtoOut }
            });
            this.setState({
              authorizedFeedback: 'error',
              message: this.getLSI('serverConnection', 'UU5_Common_VucMixin')
            });
          }
        }
      });
    } else {
      this.showError('notCall', this.getCallName('authorizeVuc', 'UU5_Common_VucMixin'), {
        mixinName: 'UU5_Common_VucMixin',
        context: { environment: Environment, calls: this.props.calls }
      });
    }
  }
  //@@viewOff:componentSpecificHelpers

  //@@viewOn:render
  //@@viewOff:render
};

export default VucMixin;
