import React from 'react';
import {
  View,
  StatusBar,
  StyleSheet,
  Image,
  Dimensions,
} from 'react-native';
import Icon from 'react-native-vector-icons/MaterialIcons';
import Camera from 'react-native-camera';
import { getToken } from '../utils/auth';
import { errors } from '../utils/error';
import { encrypt } from '../utils/helper';
import config from '../utils/config';
import { futch } from '../utils/polyfill';

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  preview: {
    flex: 1,
    justifyContent: 'flex-end',
    alignItems: 'center',
  },
  previewPic: {
    flex: 1,
  },
  overlay: {
    position: 'absolute',
    padding: 16,
    right: 0,
    left: 0,
    alignItems: 'center',
  },
  topOverlay: {
    top: 0,
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  bottomOverlay: {
    bottom: 0,
    backgroundColor: 'rgba(0,0,0,0.4)',
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
  },
  captureButton: {
    padding: 15,
    backgroundColor: 'white',
    borderRadius: 40,
  },
  typeButton: {
    padding: 5,
  },
});
class CameraComponent extends React.Component {
  constructor(props) {
    super(props);
    this.camera = null;
    this.state = {
      camera: {
        aspect: Camera.constants.Aspect.fill,
        captureTarget: Camera.constants.CaptureTarget.cameraRoll,
        type: Camera.constants.Type.back,
        orientation: Camera.constants.Orientation.auto,
      },
      isRecording: false,
      imageURI: '',
    };
    this.switchCam = this.switchCam.bind(this);
    this.recording = this.recording.bind(this);
    this.takePicture = this.takePicture.bind(this);
    this.uploadImage = this.uploadImage.bind(this);
    this.clear = this.clear.bind(this);
  }
  typeIcon= () => {
    const { back, front } = Camera.constants.Type;
    if (this.state.camera.type === back) {
      return 'camera-front';
      // icon = require('./assets/ic_camera_rear_white.png');
    } else if (this.state.camera.type === front) {
      return 'camera-rear';
    }
  };

  camButton= () => {
    if (!this.state.isRecording) {
      return 'videocam';
    } else {
      return 'stop';
    }
  };
  switchCam() {
    let newType;
    const { back, front } = Camera.constants.Type;

    if (this.state.camera.type === back) {
      newType = front;
    } else if (this.state.camera.type === front) {
      newType = back;
    }

    this.setState({
      camera: {
        ...this.state.camera,
        type: newType,
      },
    });
  }

  recording() {
    console.log(!this.state.isRecording);
    if (!this.state.isRecording) {
      if (this.camera) {
        this.camera.capture({ mode: Camera.constants.CaptureMode.video })
          .then(data => console.log(data))
          .catch(err => console.error(err));
        this.setState({ isRecording: true });
      }
      console.log('recording');
    } else {
      if (this.camera) {
        this.camera.stopCapture();
        this.setState({ isRecording: false });
      }
      console.log('stopped ');
    }
  }
  takePicture() {
    const options = { mode: Camera.constants.CaptureMode.still };
    this.camera.capture({ metadata: options })
      .then((data) => { console.log(data); this.setState({ imageURI: data.path }); })
      .catch(err => console.error(err));
  }
  uploadImage() {
    let token;
    getToken().then((Apptoken) => {
      if (!Apptoken) {
        return Promise.reject(errors.tokenMissing());
      }
      token = encrypt(Apptoken);
      const uri = `${config.apiContextPath}/resource/${token}`;
      const formData = new global.FormData();
      const file = { uri: this.state.imageURI, type: 'image/jpg', name: 'tupian.jpg' };

      formData.append('file', file);
      console.info(formData);
      futch(uri, {
        method: 'POST',
        headers: {
          'Content-Type': 'multipart/form-data',
        },
        body: formData,
      }, (progressEvent) => {
        const progress = progressEvent.loaded / progressEvent.total;
      })
        .then(request => request.responseText)// response.text())
        .then((responseData) => {
          const response = JSON.parse(responseData);
          if (response.errorCode === 0) {
            // 这里需要调用接口，对图片数据进行绑定，等待完善
            // 页面跳转，跳转到前面的详情的页面
            console.info('跳转');
            this.props.navigation.navigate('DSRInfoDetail', this.props.navigation.state.params.pID);
          }
        })
        .catch((error) => {
          console.info(error);
        });
    });
  }
  clear() {
    this.setState({ imageURI: '' });
  }

  render() {
    if (this.state.imageURI === '') {
      return (
        <View style={styles.container}>
          <StatusBar animated hidden />
          <Camera
            ref={(cam) => {
              this.camera = cam;
            }}
            style={styles.preview}
            aspect={this.state.camera.aspect}
            captureTarget={this.state.camera.captureTarget}
            type={this.state.camera.type}
            defaultTouchToFocus
            mirrorImage={false}
          />
          <View style={[styles.overlay, styles.topOverlay]}>
            <Icon.Button name={this.typeIcon()} size={36} backgroundColor="transparent" onPress={this.switchCam} />
          </View>
          <View style={[styles.overlay, styles.bottomOverlay]}>
            <Icon.Button name="photo-camera" size={48} backgroundColor="transparent" onPress={this.takePicture} />
            <Icon.Button name={this.camButton()} size={48} backgroundColor="transparent" onPress={this.recording} />
          </View>
        </View>
      );
    } else {
      return (
        <View style={styles.container}>
          <Image
            style={{ height: Dimensions.get('window').height, width: Dimensions.get('window').width }}
            source={{ uri: this.state.imageURI, isStatic: true }}
          />
          <View style={[styles.overlay, styles.bottomOverlay]}>
            <Icon.Button name="clear" size={48} backgroundColor="transparent" onPress={this.clear} />
            <Icon.Button name="done" size={48} backgroundColor="transparent" onPress={this.uploadImage} />
          </View>
        </View>
      );
    }
  }
}
export default CameraComponent;

