import * as React from 'react';
import { IRowDimensions, IStoreState } from '../../index.data';
import { get_allVisibleRowHeight_exceptFrozen, VScrollBarHelper } from './helper';
import RuntimeContext from '../../RuntimeContext';
import equals from 'fast-deep-equal';
import { AdaptiveScrollBar } from 'valor-random-ui';
import { FSM_IGNORE } from '../../constants';

interface Props {
  rowDimensions: IRowDimensions;
  loadableRowFlags: boolean[];
  scroll: number;
}

class VScrollBar extends React.Component<Props> {
  static contextType = RuntimeContext;
  context!: React.ContextType<typeof RuntimeContext>;

  constructor(props: Props) {
    super(props);
    this.handleScroll = this.handleScroll.bind(this);
  }

  shouldComponentUpdate(nextProps: Props) {
    return !equals(this.props, nextProps);
  }

  handleScroll(scroll: number) {
    const state = this.context!.store.getState();
    if (state.scrollY !== scroll) {
      this.context!.patchState({ scrollY: scroll, readyDimensions: true });
      setTimeout(() => {
        this.context!.setSheetDimensions();
      });
    }
  }

  render() {
    const state = this.context!.store.getState();
    const helper = new VScrollBarHelper(state);
    const { scroll } = this.props;
    const contentSize = get_allVisibleRowHeight_exceptFrozen(state);
    const barOffset = helper.barOffset;
    return (
      <AdaptiveScrollBar
        direction="v"
        contentSize={contentSize + state.padding.bottom}
        viewportSize={state.containerBox.h - barOffset}
        scrollSize={scroll}
        barWidth={16}
        barSize={helper.barSize}
        barStyle={{ right: 0, background: '#dedede', top: barOffset }}
        thumbStyle={{ background: '#666' }}
        visibleOn="needed"
        onScroll={this.handleScroll}
        delay={60}
        className={FSM_IGNORE}
      />
    );
  }
}

export default VScrollBar;
