import React, { useState, useContext } from 'react';
import {
  View,
  StyleSheet,
  Text,
  Dimensions,
  TouchableWithoutFeedback,
  Platform
} from 'react-native';
import { Icon, Slider } from 'react-native-elements';
import C from 'rn-class';
import {PlayerStateContext, PlayerDispatchContext, playerCommon} from './PlayerReducer';

const { width } = Dimensions.get('window');

export const PLACEHOLDER_WIDTH = width / 4;

export default PlayerControls = props => {
  const { playerData, closePlayer } = props;
  const playerDispatch = useContext(PlayerDispatchContext);
  const playerState = useContext(PlayerStateContext);
  const {paused, player, duration, currentTime} = playerState;
  const { secondsTohhmmss } = playerCommon;

  const onSetPlay = () => {
    playerDispatch({type:'paused', setPaused:!paused});
  };
  const getThumbTopFromStyleHeight = (styleHeight=40, trackHeight=4) => {
    const thumbTop = (styleHeight / 2) + (trackHeight / 2) + 
    (Platform.OS==='android'&&(styleHeight<40||trackHeight<4)?0.5:0);
    return {
      sh: {height:styleHeight},
      th: {height:trackHeight},
      tt: {top:thumbTop}
    }
  }
  const sliderLayout = getThumbTopFromStyleHeight(20,2);
  return (
    <>
      <View style={styles.container}>
        <View style={styles.placeholder} />
        <C.View cls="flx2">
          <C.View cls="flx-row jc-sb">
            <Text numerOfLine={1}>{playerData.title.replace(/\r\n|\n|\r/gm,' ')}</Text>
            <Text>{secondsTohhmmss(duration)}</Text>
          </C.View>
          <Slider
            style={sliderLayout.sh}
            trackStyle={sliderLayout.th}
            thumbTintColor="#333"
            thumbStyle={{width:10, height:10, ...sliderLayout.tt}}
            maximumValue={duration}
            value={currentTime}
            onValueChange={value => playerDispatch({type: 'seek', seekValue: Math.floor(value)})}
          />
        </C.View>
        <C.View cls="flx0.7 jc-sa ai-sa flx-row">
          { paused===false
            ?<C.EL.Icon {...C.n2cls("size8")} type="ionicon" name="md-pause" onPress={onSetPlay} />
            :<C.EL.Icon {...C.n2cls("size8")} type="ionicon" name="md-play" onPress={onSetPlay} />
          }
        </C.View>
        <C.EL.Icon {...C.n2cls("size8")} ccls="mr2" type="ionicon" name="md-close" onPress={closePlayer} />
      </View>
    </>
  );
};

const styles = StyleSheet.create({
  container: {
    ...StyleSheet.absoluteFillObject,
    flexDirection: 'row',
    justifyContent: 'space-around',
    alignItems: 'center'
  },
  placeholder: {
    width: PLACEHOLDER_WIDTH
  }
});
