// LIBRARIES
import React, { Component } from 'react'
import { Formik } from 'formik'
import { message } from 'antd';
import { connect } from "react-redux"
import { notification, Icon } from "antd"
 
// COMPONENTS
import HeaderForm from "components/Forms/HeaderForm"
import CreateSystemPreferencesForm from './components/CreateSystemPreferencesForm'
 
// HELPER FUNCTIONS
import { customAction } from "actions";
import { API_GET, API_PUT, API_POST, API_UNI_OIL } from "utils/Api";
import { apiFormValidation } from "utils/helper";
import { userDetailsSchema } from './validationSchema'
import axios from 'axios'
// import { REACT_APP_API_SYNC } from '.env'
import { getCookie } from '../../../../utils/cookie'

class CreateSystemPreferences extends Component {
  state = {
    loading: false,
    mounted: false,
    systemPreference: null,
    fileUpload: null,
    actionAndroidTypeOptions: [{label:"Update",value:"0"},{label:"Force Update",value:"1"},{label:"Silent Update",value:"2"}],
    actionIosTypeOptions: [{label:"Update",value:"0"},{label:"Force Update",value:"1"},{label:"Silent Update",value:"2"}]
  }
  async componentDidMount() {
    const { match } = this.props;
    let actionAndroidTypeDefaultValue = []
    let actionAndroidTypeDefaultKeyValue = []
    let actionIosTypeDefaultValue = []
    let actionIosTypeDefaultKeyValue = []

    try {
      let response = await API_UNI_OIL.get(`systemPreference`) 

      let actionAndroidtype = []
      let actionIostype = []

      if(response.data.data.android_action) {
        actionAndroidtype.push(response.data.data.android_action)

        if(response.data.data.android_action == 0){
            actionAndroidTypeDefaultValue.push(
              "Update"
            )
            actionAndroidTypeDefaultKeyValue.push(
              "0"
            )
        }
        else if(response.data.data.android_action == 1){
            actionAndroidTypeDefaultValue.push(
              "Force Update"
            )
            actionAndroidTypeDefaultKeyValue.push(
              "1"
            )
        }
        else if(response.data.data.android_action == 2){
          actionAndroidTypeDefaultValue.push(
              "Silent Update"
            )
            actionAndroidTypeDefaultKeyValue.push(
              "2"
            )
        }
      }

      if(response.data.data.ios_action) {
        actionIostype.push(response.data.data.ios_action)

        if(response.data.data.ios_action == 0){
            actionIosTypeDefaultValue.push(
              "Update"
            )
            actionIosTypeDefaultKeyValue.push(
              "0"
            )
        }
        else if(response.data.data.ios_action == 1){
            actionIosTypeDefaultValue.push(
              "Force Update"
            )
            actionIosTypeDefaultKeyValue.push(
              "1"
            )
        }
        else if(response.data.data.ios_action == 2){
          actionIosTypeDefaultValue.push(
              "Silent Update"
            )
            actionIosTypeDefaultKeyValue.push(
              "2"
            )
        }
      }


      this.setState({
        systemPreference: {...response.data.data},
        actionAndroidTypeDefaultValue,
        actionAndroidTypeDefaultKeyValue,
        actionIosTypeDefaultValue,
        actionIosTypeDefaultKeyValue,
        mounted: true
      })
    } catch ({response: error}) {
      notification.error({ 
        message: "Error", 
        description: <div>
          <div>Something went wrong loading data.</div>
        - { error && error.data && error.data.message }
        </div> , 
        duration: 3, 
      });
      this.setState({ mounted: false })
    }
    
  }


  handleSubmit = async (values, actions) => {
    
    const { fileUpload } = this.state;
    const { setSubmitting, setErrors } = actions;

    this.setState({loading: true})
    try {
          const headers = {
            'ContentType': 'multipart/form-data',
          }; 
          const formData = new FormData();
      
          if(fileUpload) {
            fileUpload.forEach((t, i) => {
              formData.append( `logo`, t.originFileObj);
            }); 
          } 
          
          let newNumber = values && values.contact_number_mobile 
              && values.contact_number_mobile && String(values.contact_number_mobile).split(' ').join('')
          
          values.gps && (formData.append('gps', values.gps));
          values.contact_email_address_mobile && (formData.append('contact_email_address_mobile', values.contact_email_address_mobile))
          values.contact_details && (formData.append('contact_details', values.contact_details));
          newNumber && (formData.append('contact_number_mobile', newNumber ));
          formData.append('information_guide_details', values.information_guide_details && values.information_guide_details);
          formData.append('android_version', values.android_version && values.android_version);
          formData.append('android_update_message', values.android_update_message && values.android_update_message);
          formData.append('android_action', values.android_action && values.android_action);
          formData.append('ios_version', values.ios_version && values.ios_version);
          formData.append('ios_update_message', values.ios_update_message && values.ios_update_message);
          formData.append('ios_action', values.ios_action && values.ios_action);
          
          let response = await API_UNI_OIL.post('systemPreference', formData , headers)

          if(response) {
            message.success('Record was successfully update.');  
            this.setState({loading: false})

            this.props.customAction({
              type: "SYSTEMPREFERENCES_CREATE_REQUEST",
              payload: {
                values
              }
            });
            
          }
          
        
    } catch ({response: error}) {
      if (error.status === 422) {
        apiFormValidation({ data: error.data.data, setErrors });
      }
      notification.error({ 
        message: 'Error', 
        description: <div>
          Something went wrong creating new record.
          { error && error.data && error.data.data  && error.data.data.contact_email_address_mobile 
                && (<div>- {error.data.data.contact_email_address_mobile[0]} </div>) }
          { error && error.data && error.data.data && error.data.data.contact_number_mobile
               && (<div>- {error.data.data.contact_number_mobile[0]} </div>) }
        </div>
      }); 
      this.setState({loading: false})
      setSubmitting(false);
    }
    
  }

  handleAddUser =()=> {
    this.form.submitForm()
  }

  handleFileUpload =(e)=> {
    if (Array.isArray(e)) {
      return this.setState({fileUpload: e});
    }
    return e && this.setState({fileUpload: e.fileList});
  }

  syncStratuscast = async () => {
    this.setState({loading: true})
    // try {
    //   let stratuscastAboutUs = await API_UNI_OIL.get('stratuscastAboutUs')
    // } catch (error) {
    //   // notification.error({ 
    //   //   message: 'Error', 
    //   //   description: <div>
    //   //     Something went wrong in Stratuscast About Us.
    //   //   </div>
    //   // });
    // }
    await axios.get(process.env.REACT_APP_API_SYNC+'syncstations')
      .then((response)=>{
        message.success('Successfully Sync Data.');
    })
      .catch((e)=>{
        console.log(e)
        notification.error({ 
          message: 'Error', 
          description: <div>
            Something went wrong. Please try again!
          </div>
      });
    })

    await axios.get(process.env.REACT_APP_API_SYNC+'synccities', {
      headers: {
        'Authorization': `Bearer ${getCookie('TOKEN').token}`
      }    
    })
      .then((response)=>{
        message.success('Successfully Sync Cities.');
    })
    .catch((e)=>{
      console.log(e)
      notification.error({ 
        message: 'Error', 
        description: <div>
          Something went wrong. Please try again!
        </div>
      });
    })

    // try {
    //   await axios.get('https://mobileapid.unioil.com/api/mobile/syncstations')
    // } catch (error) {
    //   notification.error({ 
    //     message: 'Error', 
    //     description: <div>
    //       Something went wrong in Stratuscast City Province.
    //     </div>
    //   });
    // }

    // try {
    //   await axios.get('https://mobileapid.unioil.com/api/mobile/syncstations')
    // } catch (error) {
    //   notification.error({ 
    //     message: 'Error', 
    //     description: <div>
    //       Something went wrong in Stratuscast Products.
    //     </div>
    //   });
    // }

    // try {
    //   await axios.get('https://mobileapid.unioil.com/api/mobile/syncstations')
    // } catch (error) {
    //   notification.error({ 
    //     message: 'Error', 
    //     description: <div>
    //       Something went wrong in Stratuscast Station.
    //     </div>
    //   });
    // }

    // message.success('Successfully Sync Data.');
    this.setState({loading: false})
  }

  render() {

    

    if(!this.state.mounted) return null;

    const { systemPreference, loading, actionAndroidTypeDefaultValue, actionAndroidTypeDefaultKeyValue, actionAndroidTypeOptions,
            actionIosTypeDefaultValue, actionIosTypeDefaultKeyValue, actionIosTypeOptions } = this.state

    return (
      <div style={{ border:'1px solid #E6ECF5' , paddingBottom: '10px'}}>
        {/* <HeaderForm 
          loading={loading}
          title="System Parameters"
          action={this.handleAddUser}
          actionBtnName="Submit"
          // cancel={()=> {console.log('cancel button')}}
          // cancelBtnName="Cancel"
        /> */}
        <div>
          <Formik
              initialValues={{
                logo: systemPreference.logo || '',
                gps: systemPreference.gps || '',
                contact_email_address_mobile: systemPreference.contact_email_address_mobile || '',
                contact_number_mobile: systemPreference.contact_number_mobile || '',
                contact_details: systemPreference.contact_details  || '',
                information_guide_details: systemPreference.information_guide_details || '',
                android_version: systemPreference.android_version || '',
                android_update_message: systemPreference.android_update_message || '',
                android_action: actionAndroidTypeDefaultKeyValue || '',
                ios_version: systemPreference.ios_version || '',
                ios_update_message: systemPreference.ios_update_message || '',
                ios_action: actionIosTypeDefaultKeyValue || '',
              }}
              ref={node => (this.form = node)}
              enableReinitialize={true}
              validationSchema={userDetailsSchema}
              onSubmit={this.handleSubmit }
              render = {(props)=> 
                <CreateSystemPreferencesForm 
                  {...props}
                  loading={loading}
                  actionAndroidTypeOptions={actionAndroidTypeOptions}
                  actionIosTypeOptions={actionIosTypeOptions}
                  handleFileUpload={this.handleFileUpload}
                  actionAndroidTypeDefaultValue={actionAndroidTypeDefaultValue}
                  actionIosTypeDefaultValue={actionIosTypeDefaultValue}
                  syncStratuscast={this.syncStratuscast}
                />
              }
          />
        </div>
      </div>
    )
  }
}


CreateSystemPreferences = connect(
  state => ({
    //userInfo: state
    //userManagement: state.userManagement,
  }),
  { customAction }
)(CreateSystemPreferences);

export default CreateSystemPreferences;
