/** Contains the base fields for a contact reuse **/
import React, { Component } from 'react';
import { Alert, Dimensions, Linking, View } from 'react-native';
import { Button, Tile } from 'react-native-elements';
import { connect } from 'react-redux';
import { ImagePicker, Permissions } from 'expo';
import { contactUpdate, profileUpdate } from '../actions';
import { PROFILE_FORM, CONTACT_FORM, SOCIAL_FORM } from './FormTypes';
import { Spacer } from './common';
import privateKeys from '../../private_keys.json';
import colors from '../config/colors.json';
import { strings } from '../locales/i18n';

const width = Dimensions.get('window').width * 0.9;
const height = width * 0.57; // ( 2 / 3.5 = 0.57) Business card dimensions
const regexObj = {};
const visionObj = {};
// Since we have duplicate keys between contact and profile we can't use this.props
// so we track what has been populated here
const propsAlreadySet = {};

class BizCard extends Component {
  constructor(props) {
    super(props);
    this.state = {
      cameraRollStatus: '',
      text: null,
      company: null,
      jobTitle: null,
      city: null,
      region: null
    };
    this.setCameraRollStatus();
  }

  /**
  * Component Will Mount
  **/
  componentWillMount() {
    if (this.props.isScanBizCardScreen) {
      this.onTakePhotoButtonPress();
    }
  }

  /**
  * Sends user to the gallery to upload image from device
  **/
  onPickImageButtonPress = async () => {
    if (this.state.cameraRollStatus !== 'granted') {
      await Permissions.askAsync(Permissions.CAMERA_ROLL)
      .then((data) => {
        if (data.status !== 'granted') {
          Alert.alert(strings('common.error.permissionDenied_cameraRoll'));
          Linking.openURL('app-settings:');
          return;
        }
      }).catch(err => console.error('askAsync camera roll error ', err));
      this.setCameraRollStatus();
    }

    const result = await ImagePicker.launchImageLibraryAsync({
      allowsEditing: true,
      aspect: [3.5, 2],
      base64: true,
      mediaTypes: ImagePicker.MediaTypeOptions.Images
    });

    if (!result.cancelled) {
      this.processImage(result);
    }
  };

  /**
  * Opens the camera for the user to take a new photo
  **/
  onTakePhotoButtonPress = async () => {
    const result = await ImagePicker.launchCameraAsync({
      allowsEditing: true,
      aspect: [4, 3],
      base64: true
    });

    if (!result.cancelled) {
      this.processImage(result);
    }
  };

  /**
  * Gets the current permission state of the app for camera roll/photos
  **/
  setCameraRollStatus = async () => {
    const { status } = await Permissions.getAsync(Permissions.CAMERA_ROLL);
    this.setState({ cameraRollStatus: status });
  }

  /**
  * Takes the chosen image in base64 and saves the base64 and submits it for text recognition
  **/
  processImage = async (response) => {
    this.setState({ text: strings('bizCard.loading') });
    propsAlreadySet.base64 = true;
    if (this.props.formType === CONTACT_FORM) {
      this.props.contactUpdate({ prop: 'contactBizCardImg', value: response.uri });
    } else if (this.props.formType === PROFILE_FORM) {
      this.props.profileUpdate({ prop: 'profileBizCardImg', value: response.uri });
    }

    const body = {
      requests: [
        {
          image: {
            content: response.base64,
          },
          features: [
            {
              type: 'DOCUMENT_TEXT_DETECTION',
            }
          ]
        },
      ],
    };

    const visionResponse = await fetch(`https://vision.googleapis.com/v1/images:annotate?key=${privateKeys.googleapis.GOOGLE_API_KEY}`, {
      method: 'POST',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(body)
    });
    const visionParsed = await visionResponse.json();
    // Checks that some text was found before trying to read it
    if (visionParsed.responses[0].fullTextAnnotation && visionParsed.responses[0].fullTextAnnotation.text) {
      this.setState({
        text: visionParsed.responses[0].fullTextAnnotation.text,
      });
      console.log('STATE.TEXT\n', this.state.text);
      this.extractImageContext(this.state.text);
    }
  }

  /**
  * Extracts information from the OCR text and separates it based on context
  **/
  extractImageContext = async (imageText) => {
    const body = {
      encodingType: 'UTF8',
      document: {
        type: 'PLAIN_TEXT',
        content: imageText
      }
    };

    const languageResponse = await fetch(`https://language.googleapis.com/v1/documents:analyzeEntities?key=${privateKeys.googleapis.GOOGLE_API_KEY}`, {
      method: 'POST',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(body)
    });
    const languageParsed = await languageResponse.json();
    // console.log('languageParsed,entities is\n', languageParsed.entities);
    this.populatePhoneField(imageText);
    this.extractFullAddress(imageText);

    // Try fullAddress first
    if (regexObj.fullAddress) {
      this.populateFieldsFromFullAddress();
    }

    this.performVisionParsing(languageParsed.entities);

    if (!propsAlreadySet.street || !propsAlreadySet.city || !propsAlreadySet.region || !propsAlreadySet.postalCode) {
      this.extractSecondLine(imageText);
      this.populateAddressByLine(imageText);
    }

    if (!propsAlreadySet.email) {
      this.extractEmail(imageText);
    }

    if (!propsAlreadySet.website) {
      this.populateWebsiteField(imageText);
    }

    if (!propsAlreadySet.company) {
      this.populateCompanyField();
    }
  }

  /**
  * Populates fields based on the common data assignment based on the data below
  * 0 - PROPER 1 - PERSON === NAME
  * 0 - PROPER 1 - ORGANIZATION === ADDRESS OR COMPANY
  * 0 - PROPER 1 - LOCATION === ADDRESS
  * 0 - PROPER 1 - OTHER === EMAIL OR WEBSITE
  * 0 - PROPER 1 - WORKOFART === ADDRESS
  * 0 - COMMON 1 - PERSON === TITLE
  **/
  performVisionParsing = (languageEntities) => {
    languageEntities.forEach((entity) => {
      for (let i = 0; i < entity.mentions.length; i++) {
        switch (entity.mentions[i].type) {
          case 'PROPER':
            // PROPER - PERSON is the name
            // We don't get the name from regex so just set it here
            if (entity.type === 'PERSON' && !propsAlreadySet.firstName) {
              this.populateNameField(entity.name);
            // PROPER - LOCATION is the address
            } else if (entity.type === 'LOCATION') {
              this.extractAddressFromVisionFields(entity.name);
            // PROPER - ORGANIZATION is the address or company
            } else if (entity.type === 'ORGANIZATION') {
              if (this.isAddressField(entity.name)) {
                this.extractAddressFromVisionFields(entity.name);
              } else {
                this.extractAddressOrCompany(entity.name);
              }
            // PROPER - WORKOFART is the address
            } else if (entity.type === 'WORKOFART') {
              this.extractAddressFromVisionFields(entity.name);
            // PROPER - OTHER is the email or website
            } else if (entity.type === 'OTHER') {
              this.extractEmailOrWebsite(entity.name);
            }
            break;

          case 'COMMON':
            // COMMON - PERSON is the jobTitle
            // We don't get the jobTitle from regex so just set it here
            if (entity.type === 'PERSON' && !propsAlreadySet.jobTitle) {
              propsAlreadySet.jobTitle = true;
              this.setState({ jobTitle: entity.name });
            }
            break;

          default:
            break;
        }
      }
    });
    this.combineTitleAndCompany();
    this.combineLocation();
  }

  /**
  * Uses regex to find phone number from the imageText.
  * Since phone isn't typically extracted from the
  * vision process we set the phone now
  **/
  populatePhoneField(imageText) {
    try {
      const phoneRegex = /\(?\d{3}\)?-?\.?\s?\d{3}-?.?\s?\d{4}/;
      let extractedPhone = '';

      if (Array.isArray(imageText)) {
        extractedPhone = imageText[0].match(phoneRegex);
      } else {
        extractedPhone = imageText.match(phoneRegex);
      }

      if (extractedPhone) {
        propsAlreadySet.primaryPhone = true;
        if (this.props.formType === CONTACT_FORM) {
          this.props.contactUpdate({ prop: 'primaryPhone', value: extractedPhone[0] });
        } else if (this.props.formType === PROFILE_FORM) {
          this.props.profileUpdate({ prop: 'primaryPhone', value: extractedPhone[0] });
        }
      }
    } catch (error) {
      console.log(`Could not populate phone from '${imageText}': ${error}`);
    }
  }

  /**
  * Sets the firstName and lastName fields
  **/
  populateNameField(proposedName) {
    const nameArray = proposedName.split(' ');
    let lastNameStr = '';

    switch (true) {
      case (nameArray.length > 3):
        return;
      case (nameArray.length === 3):
        lastNameStr = `${nameArray[1]} ${nameArray[2]}`;
        break;
      case (nameArray.length === 2):
        lastNameStr = nameArray[1];
        break;
      default:
        break;
    }

    propsAlreadySet.firstName = true;
    let fullName = '';
    if (lastNameStr) {
      fullName = `${nameArray[0]} ${lastNameStr}`;
    } else {
      fullName = nameArray[0];
    }
    if (this.props.formType === CONTACT_FORM) {
      this.props.contactUpdate({ prop: 'firstName', value: nameArray[0] });
      this.props.contactUpdate({ prop: 'fullName', value: fullName });
      if (lastNameStr) {
        this.props.contactUpdate({ prop: 'lastName', value: lastNameStr });
      }
    } else if (this.props.formType === PROFILE_FORM) {
      this.props.profileUpdate({ prop: 'firstName', value: nameArray[0] });
      this.props.profileUpdate({ prop: 'fullName', value: fullName });
      if (lastNameStr) {
        this.props.profileUpdate({ prop: 'lastName', value: lastNameStr });
      }
    }
  }

  /**
  * Performs regex and populates fields if found
  **/
  extractEmail(textToParse) {
    try {
      const emailRegex = /[a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+/i;
      let extractedEmail = '';

      if (Array.isArray(textToParse)) {
        extractedEmail = textToParse[0].match(emailRegex);
      } else {
        extractedEmail = textToParse.match(emailRegex);
      }

      if (extractedEmail) {
        propsAlreadySet.email = true;
        regexObj.email = extractedEmail;
        if (this.props.formType === CONTACT_FORM) {
          this.props.contactUpdate({ prop: 'contactEmail', value: extractedEmail[0] });
        } else if (this.props.formType === PROFILE_FORM) {
          this.props.profileUpdate({ prop: 'profileEmail', value: extractedEmail[0] });
        }
      }
    } catch (error) {
      console.log(`Could not extract email from '${textToParse}': ${error}`);
    }
  }

  /**
  * Vision extraction has already been attempted
  * Extracts the website from image text first and if unsuccessful
  * then just get it from the email domain
  **/
  populateWebsiteField(imageText) {
    try {
      if (!propsAlreadySet.website) {
        this.extractWebsite(imageText);
      }
      if (!propsAlreadySet.website && propsAlreadySet.email) {
        this.extractWebsite(regexObj.email);
      }
    } catch (error) {
      console.log('Could not populate website', error);
    }
  }

  /**
  * Performs regex and populates fields if found
  **/
  extractWebsite(textToParse) {
    try {
      const websiteRegex = /w?w?w?\.?[a-z-]{2,}\.[a-z]{2,}\.?[a-z]*/i;
      let extractedWebsite = '';

      if (Array.isArray(textToParse)) {
        extractedWebsite = textToParse[0].match(websiteRegex);
      } else {
        extractedWebsite = textToParse.match(websiteRegex);
      }

      if (extractedWebsite) {
        propsAlreadySet.website = true;
        if (this.props.formType === CONTACT_FORM) {
          this.props.contactUpdate({ prop: 'website', value: extractedWebsite[0] });
        } else if (this.props.formType === PROFILE_FORM) {
          this.props.profileUpdate({ prop: 'website', value: extractedWebsite[0] });
        }
      }
    } catch (error) {
      console.log(`Could not extract website from '${textToParse}': ${error}`);
    }
  }

  /**
  * Extracts the company from vision first and from image text second
  * If both of those fail then just get it from the email domain
  **/
  populateCompanyField() {
    try {
      if (propsAlreadySet.company) {
        return;
      }
      if (visionObj.company) {
        this.extractCompanyFromVision();
      } else if (propsAlreadySet.email) {
        this.extractCompanyFromEmail();
      }
    } catch (error) {
      console.log('Could not populate company', error);
    }
  }

  /**
  * Populates the company from the vision response
  **/
  extractCompanyFromVision() {
    propsAlreadySet.company = true;
    this.setState({ company: visionObj.company });
  }

  /**
  * Extracts the company from the email
  **/
  extractCompanyFromEmail() {
    const { email } = regexObj;
    // Sets the company to be anything between the '@' and '.'
    let atIndex;
    let dotIndex;
    let foundAt = false;
    for (let i = 0; i < email.length; i++) {
      if (email[i] === '@') {
        atIndex = i + 1;
        foundAt = true;
      } else if (foundAt && email[i] === '.') {
        dotIndex = i;
      }
    }

    const company = email.slice(atIndex, dotIndex);
    propsAlreadySet.company = true;
    this.setState({ company });
  }

  /**
  * Combines the jobTitle and Company fields into one field for the details section
  **/
  combineTitleAndCompany() {
    const company = this.state.company || '';
    const jobTitle = this.state.jobTitle || '';
    if (!company && !jobTitle) {
      return;
    }

    const titleAndCompany = `${jobTitle} ${company}`;
    if (this.props.formType === CONTACT_FORM) {
      this.props.contactUpdate({ prop: 'titleAndCompany', value: titleAndCompany });
    } else if (this.props.formType === PROFILE_FORM) {
      this.props.profileUpdate({ prop: 'titleAndCompany', value: titleAndCompany });
    }
  }

  /**
  * Combines the region and state fields into one field for the details section
  **/
  combineLocation() {
    const city = this.state.city || '';
    const region = this.state.region || '';
    if (!city && !region) {
      return;
    }
    const location = region ? `${city}, ${region}` : city;
    if (this.props.formType === CONTACT_FORM) {
      this.props.contactUpdate({ prop: 'location', value: location });
    } else if (this.props.formType === PROFILE_FORM) {
      this.props.profileUpdate({ prop: 'location', value: location });
    }
  }

  /**
  * Uses regex to find the full address for comparison to vision response
  **/
  extractFullAddress(imageText) {
    try {
      const fullAddressRegex = /\d+ [a-zA-Z,.# 0-9]+[\s |][a-zA-Z ]+, [A-Z]{2}\s\d{5}/;
      const extractedFullAddress = imageText.match(fullAddressRegex);
      if (extractedFullAddress) {
        regexObj.fullAddress = extractedFullAddress;
      }
    } catch (error) {
      console.log(`Could not extract full address from '${imageText}': ${error}`);
    }
  }

  /**
  * Uses regex to find the first line of address for comparison to vision response
  **/
  extractFirstLine(textToParse) {
    try {
      regexObj.firstLine = '';
      const firstLineRegex = /\d+ [a-zA-Z.,# 0-9]+\s/;
      let extractedFirstLine = '';

      if (Array.isArray(textToParse)) {
        extractedFirstLine = textToParse[0].match(firstLineRegex);
      } else {
        extractedFirstLine = textToParse.match(firstLineRegex);
      }

      if (extractedFirstLine && !propsAlreadySet.street) {
        propsAlreadySet.street = true;
        if (this.props.formType === CONTACT_FORM) {
          this.props.contactUpdate({ prop: 'street', value: extractedFirstLine[0] });
        } else if (this.props.formType === PROFILE_FORM) {
          this.props.profileUpdate({ prop: 'street', value: extractedFirstLine[0] });
        }
      }
    } catch (error) {
      console.log(`Could not extract first line of address from'${textToParse}': ${error}`);
    }
  }

  /**
  * Uses regex to find the second line of address for comparison to vision response
  **/
  extractSecondLine(textToParse) {
    try {
      regexObj.secondLine = '';
      const secondLineRegex = /[a-zA-Z ]+, [A-Z]{2}\s\d{5}/;
      let extractedSecondLine = '';

      if (Array.isArray(textToParse)) {
        extractedSecondLine = textToParse[0].match(secondLineRegex);
      } else {
        extractedSecondLine = textToParse.match(secondLineRegex);
      }

      if (extractedSecondLine) {
        regexObj.secondLine = extractedSecondLine[0];
        return true;
      }
      return false;
    } catch (error) {
      console.log(`Could not extract second line of address from '${textToParse}': ${error}`);
    }
  }

  /**
  * Uses regex to find the city
  **/
  extractCity(textToParse) {
    try {
      regexObj.city = '';
      const cityRegex = /[a-zA-Z ]+,/;
      let extractedCity = '';

      if (Array.isArray(textToParse)) {
        extractedCity = textToParse[0].match(cityRegex);
      } else {
        extractedCity = textToParse.match(cityRegex);
      }

      if (extractedCity) {
        extractedCity = extractedCity[0].replace(/,/, '');
        propsAlreadySet.city = true;
        this.setState({ city: extractedCity });
        if (this.props.formType === CONTACT_FORM) {
          this.props.contactUpdate({ prop: 'city', value: extractedCity });
        } else if (this.props.formType === PROFILE_FORM) {
          this.props.profileUpdate({ prop: 'city', value: extractedCity });
        }
      }
    } catch (error) {
      console.log(`Could not extract city from '${textToParse}': ${error}`);
    }
  }

  /**
  * Uses regex to find the region (state)
  **/
  extractRegion(textToParse) {
    try {
      regexObj.region = '';
      const regionRegex = /, [A-Z]{2}/;
      let extractedRegion = '';

      if (Array.isArray(textToParse)) {
        extractedRegion = textToParse[0].match(regionRegex);
      } else {
        extractedRegion = textToParse.match(regionRegex);
      }

      if (extractedRegion) {
        extractedRegion = extractedRegion[0].replace(/, /, '');
        propsAlreadySet.region = true;
        this.setState({ region: extractedRegion });
        if (this.props.formType === CONTACT_FORM) {
         this.props.contactUpdate({ prop: 'region', value: extractedRegion });
        } else if (this.props.formType === PROFILE_FORM) {
          this.props.profileUpdate({ prop: 'region', value: extractedRegion });
        }
      }
    } catch (error) {
      console.log(`Could not extract region from ${textToParse}' ${error}`);
    }
  }

  /**
  * Uses regex to find the postalCode
  **/
  extractPostalCode(textToParse) {
    try {
      regexObj.postalCode = '';
      const zipRegex = /\d{5}/;
      let extractedPostalCode = '';

      if (Array.isArray(textToParse)) {
        extractedPostalCode = textToParse[0].match(zipRegex);
      } else {
        extractedPostalCode = textToParse.match(zipRegex);
      }

      if (extractedPostalCode) {
        propsAlreadySet.postalCode = true;
        if (this.props.formType === CONTACT_FORM) {
          this.props.contactUpdate({ prop: 'postalCode', value: extractedPostalCode[0] });
        } else if (this.props.formType === PROFILE_FORM) {
          this.props.profileUpdate({ prop: 'postalCode', value: extractedPostalCode[0] });
        }
      }
    } catch (error) {
      console.log(`Could not extract postalCode from '${textToParse}': ${error}`);
    }
  }

  /**
  * Checks if a field is an address field of some form
  **/
  isAddressField(textToParse) {
    const fullAddressRegex = /\d+ [a-zA-Z,.# 0-9]+[\s |][a-zA-Z ]+, [A-Z]{2}\s\d{5}/;
    const foundFullAddress = textToParse.match(fullAddressRegex);

    const firstLineRegex = /\d+ [a-zA-Z.,# 0-9]+\s/;
    const foundFirstLine = textToParse.toString().match(firstLineRegex);

    const secondLineRegex = /[a-zA-Z ]+, [A-Z]{2}\s\d{5}/;
    const foundSecondLine = textToParse.match(secondLineRegex);

    const cityRegex = /[a-zA-Z ]+,/;
    const foundCity = textToParse.match(cityRegex);

    const regionRegex = /, [A-Z]{2}/;
    const foundRegion = textToParse.match(regionRegex);

    const zipRegex = /\d{5}/;
    const foundPostalCode = textToParse.match(zipRegex);

    return foundFullAddress || foundFirstLine || foundSecondLine || foundCity || foundRegion || foundPostalCode;
  }

  /**
  * Since the regex for full address is so strict if we found something that
  * likely means we have the full address so we'll just use that and not
  * look at the vision response since address isn't that reliable
  **/
  populateFieldsFromFullAddress() {
    // Populate the street
    this.extractFirstLine(regexObj.fullAddress[0]);

    // Get the second line then split into city, region, and zip
    this.extractSecondLine(regexObj.fullAddress[0]);
    if (regexObj.secondLine) {
      // Populate the city, region, and postalCode fields
      this.extractCity(regexObj.secondLine);
      this.extractRegion(regexObj.secondLine);
      this.extractPostalCode(regexObj.secondLine);
    }
  }

  /**
  * Uses the vision response to find remaining address fields
  **/
  extractAddressFromVisionFields(textToParse) {
    // Check for Street if not found
    if (!propsAlreadySet.street) {
      this.extractFirstLine(textToParse);
    }

    // Check for city if not found
    if (!propsAlreadySet.city) {
      this.extractCity(textToParse);
    }

    // Check for region if not found
    if (!propsAlreadySet.region) {
      this.extractRegion(textToParse);
    }

    // Check for postalCode if not found
    if (!propsAlreadySet.postalCode) {
      this.extractPostalCode(textToParse);
    }
  }

  /**
  * PROPER - ORGANIZATION is address or company
  * This tries to determine which one it is
  **/
  extractAddressOrCompany(textToParse) {
    const firstLineRegex = /\d+ [a-zA-Z.,# 0-9]+\s/;
    const extractedFirstLine = textToParse.toString().match(firstLineRegex);

    const secondLineRegex = /[a-zA-Z ]+, [A-Z]{2}\s\d{5}/;
    const extractedSecondLine = textToParse.match(secondLineRegex);

    // If we didn't find either address line then assume it's company
    if (!extractedFirstLine && !extractedSecondLine && !propsAlreadySet.company) {
      visionObj.company = textToParse;
      this.populateCompanyField();
    }
    // If we found either line then extract the info from it
    if (extractedFirstLine || extractedSecondLine) {
      this.populateAddressByLine(textToParse);
    }
  }

  /**
  * PROPER - OTHER is email or website
  * This tries to determine which one it is
  **/
  extractEmailOrWebsite(textToParse) {
    if (textToParse.indexOf('@') > 1) {
      if (!propsAlreadySet.email) {
        this.extractEmail(textToParse);
      }
    } else if (!propsAlreadySet.website) {
      this.extractWebsite(textToParse);
    }
  }

  /**
  * Looks at the remaining fields and try to populate them using regex
  **/
  populateAddressByLine(textToParse) {
    const { secondLine } = regexObj;
    if (!propsAlreadySet.street) {
      this.extractFirstLine(textToParse);
    }
    if (secondLine) {
      if (!propsAlreadySet.city) {
        this.extractCity(secondLine);
      }
      if (!propsAlreadySet.region) {
        this.extractRegion(secondLine);
      }
      if (!propsAlreadySet.postalCode) {
        this.extractPostalCode(secondLine);
      }
    }
  }

  /**
  * Renders the business card tile
  **/
  renderBusinessCardTile() {
    let base64 = '';
    if (this.props.formType === CONTACT_FORM) {
      base64 = this.props.contactBizCardImg;
    } else if (this.props.formType === PROFILE_FORM) {
      base64 = this.props.profileBizCardImg;
    } else if (this.props.formType === SOCIAL_FORM) {
      base64 = this.props.socialBizCardImg;
    }
    if (base64) {
      return (
        <Tile
          imageSrc={{ uri: base64 }}
          featured
          containerStyle={styles.tileContainerStyle}
          imageContainerStyle={styles.tileStyle}
        />
      );
    }
    return (
      <Tile
        featured
        title={strings('bizCard.photoTile_noCard')}
        containerStyle={styles.tileContainerStyle}
        imageContainerStyle={styles.tileStyle}
      />
    );
  }

  /**
  * Renders the photo buttons
  **/
  renderPhotoButtons() {
    if (this.props.formType === SOCIAL_FORM || !this.props.isEditMode) {
      return <View style={styles.buttonContainerStyle} />;
    }
    return (
      <View style={styles.buttonContainerStyle}>
        <Button
          onPress={this.onPickImageButtonPress.bind(this)}
          title={strings('common.buttons.uploadImage')}
          buttonStyle={styles.halfButtonStyle}
          disabled={this.props.loading}
          icon={{ name: 'folder' }}
        />

        <Button
          onPress={this.onTakePhotoButtonPress.bind(this)}
          title={strings('common.buttons.takePhoto')}
          buttonStyle={styles.halfButtonStyle}
          disabled={this.props.loading}
          icon={{ name: 'photo-camera' }}
        />
      </View>
    );
  }

  /**
  * Render method
  **/
  render() {
    if (this.props.isEditMode) {
      return (
        <View style={styles.viewStyle}>
          {this.renderBusinessCardTile()}
          {this.renderPhotoButtons()}
        </View>
      );
    }

    return (
      <View style={styles.viewStyle}>
        <Spacer space={45} />
        {this.renderBusinessCardTile()}
        {this.renderPhotoButtons()}
      </View>
    );
  }
}

const styles = {
  tileContainerStyle: {
    height,
    width,
    marginTop: 15,
    marginBottom: 15
  },
  tileStyle: {
    height,
    width
  },
  buttonContainerStyle: {
    flex: 2,
    marginTop: 15,
    flexDirection: 'row',
    justifyContent: 'center'
  },
  halfButtonStyle: {
    backgroundColor: colors.buttonBlue,
    flex: 1,
    borderRadius: 5
  },
  viewStyle: {
    flex: 1,
    flexDirection: 'column',
    justifyContent: 'center',
    alignItems: 'center'
  }
};

/**
* Map State To Props
**/
const mapStateToProps = (state) => {
  const {
    profileBizCardImg,
  } = state.profileForm;

  const {
    contactBizCardImg,
  } = state.contactForm;

  const {
    socialBizCardImg,
  } = state.socialContacts;

  return { profileBizCardImg, contactBizCardImg, socialBizCardImg };
};

export default connect(mapStateToProps, {
  contactUpdate, profileUpdate
})(BizCard);
