import React, {Component} from 'react';
import {
  View,
  Text,
  TouchableOpacity,
  StyleSheet,
  Image,
  ImageStore,
  Platform,
  Alert,
  Dimensions
} from 'react-native';
import CameraRoll from '@react-native-community/cameraroll';
import Icon from 'react-native-vector-icons/FontAwesome5';
import AmazingCropper from 'react-native-amazing-cropper';
import {colors} from '../../assets/styles/colors-theme';
import LoadingView from '../../common/loading';
import history from '../../common/history';
import CustomCropperFooter from '../../common/CustomCropperFooter';
import NaviBar from '../../components/navi-bar';
import Migrations from '../../services/realm/Mirgrations';
import {inject, observer} from 'mobx-react';
import {observable} from 'mobx';
import AsyncStorageHelper from '../../common/asyncStorageHelper';
import convertLocalIdentifierToAssetLibrary from '../../services/convertLocalIdentifierToAssetLibrary';

const asyncStorageHelper = new AsyncStorageHelper();

@inject('appStore')
@observer
export default class CropImage extends Component {
  static navigationOptions = {
    gesturesEnabled: false,
  };

  @observable
  finish = false;

  @observable
  imageSize = {height: 100, width: 100};

  @observable
  rectangleCoordinates = {
    topLeft: {x: 10, y: 10},
    topRight: {x: 10, y: 10},
    bottomRight: {x: 10, y: 10},
    bottomLeft: {x: 10, y: 10},
  };

  constructor(props) {
    super(props);
    this.store = props.appStore;
    this.state = {
      avatarSource: null,
      image: null,
      imageData: this.props.navigation.state.params.data,
    };
  }

  componentWillMount() {
    const imageData = this.props.navigation.state.params.data;
    // const source = { uri: imageData.uri };
    this.setState({image: this.state.imageData.uri});
    this.imageSize.height = imageData.height;
    this.imageSize.width = imageData.width;
  }
  saveImageHandler(Imageuri) {
    return {
      id: this.state.imageData.id,
      name: this.state.imageData.id,
      type: this.state.imageData.type,
      createDate: this.state.imageData.createDate,
      uri: Imageuri,
      mime: this.state.imageData.mime,
      height: this.state.imageData.height,
      width: this.state.imageData.width,
    };
  }

  saveAndroidImageHandler(Imageuri) {
    return {
      id: this.state.imageData.id,
      name: this.state.imageData.id,
      type: this.state.imageData.type,
      createDate: this.state.imageData.createDate,
      uri: Imageuri,
      mime: this.state.imageData.mime,
      height: this.state.imageData.height,
      width: this.state.imageData.width,
    };
  }

  phChange(ph) {
    const appleId = ph.substring(5, 41);
    const ext = 'JPG';
    return `assets-library://asset/asset.${ext}?id=${appleId}&ext=${ext}`;
  }

  saveImage(imageURL) {
    var self = this;
    var promise = CameraRoll.saveToCameraRoll(imageURL);
    promise
      .then(function(result) {
        console.log(result);
        self.setState({image: result});
        console.log(self.state.image);
        if (Platform.OS === 'ios') {
          self.store.apartmentDataDoc.push(self.saveImageHandler(result));
        } else {
          self.store.apartmentDataDoc.push(
            self.saveAndroidImageHandler(result),
          );
        }

        console.log(self.store.apartmentDataDoc);
        self.store.loading = false;
      })
      .catch(function(error) {
        self.store.loading = false;
        console.log('Save failed！\n' + error);
      });
  }

  removeIMageTag(croppedImageUri) {
    ImageStore.getBase64ForTag(
      croppedImageUri,
      base64Image => {
        // send image to server or save it locally
        ImageStore.removeImageForTag(croppedImageUri);
        this.saveImage(croppedImageUri);
      },
      err => {
        this.store.loading = false;
      },
    );
  }

  componentDidMount() {
    asyncStorageHelper.getData('image', image => {
      if (image != null) {
        console.log(image);
        const source = {uri: image};
        this.setState({avatarSource: source});
      }
    });
  }

  updateImage(image, newCoordinates) {
    this.setState({
      image,
    });

    this.rectangleCoordinates = newCoordinates;
  }

  onDone = croppedImageUri => {
    if (this.finish === false) {
      this.finish = true;
      this.store.loading = true;
      console.log('croppedImageUri = ', croppedImageUri);
      // if (Platform.OS === 'ios') {
      //   ImageStore.getBase64ForTag(
      //     croppedImageUri,
      //     base64Image => {
      //       // send image to server or save it locally
      //       //  ImageStore.removeImageForTag(croppedImageUri);
      //       this.saveImage(croppedImageUri);
      //     },
      //     err => {
      //       this.store.loading = false;
      //     },
      //   );
      // } else {
      //   // send image to server
      // }
      // navigate to the next page of your application
      // Actions.home();
      // this.props.navigation.goBack();
      // history.goBack(this,this);
      this.saveImage(croppedImageUri);
      history.goBack(this, this);
    }
  };

  onCancel = () => {
    // navigate back
    // Actions.pop();
  };

  render() {
    return (
      <View style={{flex: 1}}>
        <AmazingCropper
          footerComponent={<CustomCropperFooter />}
          onDone={this.onDone}
          onCancel={this.onCancel}
          imageUri={this.state.image}
          imageWidth={this.imageSize.width}
          imageHeight={this.imageSize.height}
          NOT_SELECTED_AREA_OPACITY={0.3}
          BORDER_WIDTH={20}
          COMPONENT_HEIGHT={Dimensions.get('window').height - 100}
        />
      </View>
    );
  }
}

const styles = StyleSheet.flatten({
  button: {
    marginTop: 20,
    width: 100,
    height: 40,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: colors.statusBarColor,
  },
  buttonText: {
    color: '#fff',
  },
});
