/** Main screen for viewing profiles **/
import React, { Component } from 'react';
import { KeyboardAvoidingView, Platform, ScrollView, View } from 'react-native';
import { Button } from 'react-native-elements';
import Footer from '../../components/common/Footer';
import HeaderRight from '../../components/common/HeaderRight';
import { Spacer } from '../../components/common';
import ProfileForm from '../../components/forms/ProfileForms/ProfileForm';
import { getUserProfiles } from '../../utils/profile';
import { showFlashErrorMessage } from '../../utils/errorHandler';
import styles from './styles';

export default class ProfileHomeScreen extends Component {
  static navigationOptions = ({ navigation }) => 
    ({
      title: 'Business Profile',
      headerLeft: (
        <Button
          icon={{
            name: 'settings',
            type: 'simple-line-icon',
            color: styles.colors.middleGrey,
            size: 30
          }}
          onPress={() => { 
            navigation.navigate('DrawerOpen');
          }}
          backgroundColor={styles.colors.transparent}
        />
      ),
      headerRight: <HeaderRight navigation={navigation} />
    });

  constructor(props) {
    super(props);
    this.state = {
      profiles: [],
      loading: false,
      profileFormMode: 'view'//props.profileFormMode
    };
  }

  componentDidMount() {
    this.getUserProfiles();
  }

  getUserProfiles() {
    if (!this.state.profiles.length === 0) {
      this.setState({
        loading: true
      }, async () => {
        try {
          const { profiles, defaultProfile } = await getUserProfiles();
          this.setState({
            loading: false,
            profiles, //these two states will be replaced with calls to realm to save the state in the apps memory db
            defaultProfile
          });
        } catch (error) {
          showFlashErrorMessage(error);
        }
      });
    }
  }

  /**
  * Returns the main content for the screen
  **/
  renderContent() {
    return (
      <View style={styles.mainScreenViewStyle}>
        <View>
          <ScrollView>
            <ProfileForm
              profileFormMode={this.state.profileFormMode}
              profiles={this.state.profiles}
              defaultProfile={this.props.defaultProfile}
            />
            <Spacer space={80} />
          </ScrollView>
        </View>

        <View style={styles.mainFooterStyle}>
          <Footer
            {...this.props}
            index={4}
            profileIndex={this.props.profileIndex}
          />
        </View>
      </View>
    );
  }

  /**
  * Render method
  **/
  render() {
    if (Platform.OS === 'android') {
      return this.renderContent();
    }

    //iOS
    return (
      <KeyboardAvoidingView
        style={{ flex: 1 }}
        keyboardVerticalOffset={90}
        behavior="padding"
      >
        {this.renderContent()}
      </KeyboardAvoidingView>
    );
  }
}
