import React,{Component} from 'react'
import {View,StyleSheet,Text,Image,Alert} from 'react-native'
import Button from 'apsl-react-native-button'
import {Fumi} from 'react-native-textinput-effects';
let theme=require('./../../utils/theme.json');
let route=require('./../../route.json');
import I18n from 'react-native-i18n'
import * as Animatable from 'react-native-animatable';
import {validateUser, valifateAgent, saveNewuser, readUser} from "./../../webservice/AuthApi"
import Icon from 'react-native-vector-icons/MaterialIcons'
import {responsiveWidth,responsiveHeight} from 'react-native-responsive-dimensions'
import {IlinkEmitter} from "./../../utils/events"
export  default  class ActivateAccount extends Component{
    static navigatorStyle = {
        drawUnderNavBar: true,
        navBarHidden:true,
        statusBarTextColorScheme: 'light',
    };
    static options(passProps){
        return {
            topBar:{
                visible:false,
                drawBehind:true
            },
            statusBar:{
                drawBehind:true
            }

        }
    }
    constructor(props){
        super(props)
        const {navigation}=this.props
        this.type=navigation.getParam('type',0)
        this.user=navigation.getParam('user',null)
        this.state=this.initState()
    }
    initState(){
        return {
            user:this.user,
            userSimpleLoading:false
        }
    }
    render(){
        return this.type===0?
                this.renderUserSimpleActivation()
            :this.renderAgentActivation();
    }
    async gotoHome(){
        let readU=await readUser()
        let road="";
        if(!readU.category)
            road="App"
        else {
            switch (readU.category) {
                case 'geolocated':
                    road="AgentApp"
                    break;
                case 'super':
                    road="adminApp"
                    break
                default:
                    road="supAdminApp"
            }
        }

        this.props.navigation.navigate(road)


    }
     tryToActive() {
        let {activateSimple,user}=this.state;
        const validation_code=user.validation_code
         this.setState({userSimpleLoading:true});
        const isSame=validation_code===activateSimple
        if(isSame){

            validateUser(user).then(async (result)=>{
                console.log(result);
                if(result.success!==undefined){
                    Alert.alert("",I18n.t('ACCOUNT_ACTIVATE_TEXT'),[{text:"Ok",onPress:()=>{
                            var us=result.user
                            saveNewuser(us)
                            this.gotoHome()
                        }}])
                  }else{
                    Alert.alert("",result.message,[{text:"Ok",onPress:()=>{}}])
                }
                this.setState({userSimpleLoading:false});
            }).catch((e)=>{
                console.warn(e)

                this.setState({userSimpleLoading:false});
                this.userValidate.shake(800)
            })

        }else{
            setTimeout(()=>{
                this.setState({userSimpleLoading:false});
                this.userValidate.shake(800)
            },2000)
        }
    }

    renderUserSimpleActivation() {
        const text=I18n.t('ACTIVATE_ACCOUNT')

        return (
            <View style={{
                backgroundColor:theme.primary,
                flex:1,
                justifyContent:'center',
                alignItems:'center',
            }}>
                <View style={{flexDirection:'row',alignItems:'center',justifyContent:'center'}}>
                    <Image style={{width:responsiveWidth(90),resizeMode: 'contain',}} source={require('./../../datas/img/icon3.png')}/>

                </View>
                <Text style={styles.titleText}>{I18n.t('LAST_STEP')}</Text>
                <Text style={styles.descriptionText}>{I18n.t('LAST_STEP_TEXT')}</Text>
                <Animatable.View ref={(comp)=>{this.userValidate=comp}}>

                <Fumi iconClass={Icon} iconName={"lock"} iconSize={24} style={styles.inputkey}
                      onChangeText={(text)=>{
                          console.warn(text)
                          this.setState({activateSimple:text})
                      }}

                />
                </Animatable.View>
                <Button style={styles.btnActive}
                        isLoading={this.state.userSimpleLoading}

                        textStyle={styles.btnTextActive}
                        onPress={()=>this.tryToActive()}
                >{text}</Button>

            </View>)
    }

    renderAgentActivation() {
        console.warn(this.state.user)

        switch(this.state.user.category){
            default:
                return this.renderGeoLocatedActivation();
                break;
            case "hyper":
                return this.renderHypervisorActivation();
                break
        }

    }

    renderGeoLocatedActivation() {
        const text=I18n.t('ACTIVATE_ACCOUNT')
        return (<View style={{
            backgroundColor:theme.primaryDarkAdvanced,
            flex:1,
            justifyContent:'center',
            alignItems:'center',
        }}>
            <View style={{flexDirection:'row',alignItems:'center',justifyContent:'center'}}>
            <Image style={{width:responsiveWidth(90),resizeMode: 'contain',}} source={require('./../../datas/img/icon3.png')}/>

            </View>

            <Text style={styles.titleText}>{I18n.t('LAST_STEP')}</Text>
            <Text style={styles.descriptionText}>{I18n.t('LAST_STEP_TEXT')}</Text>
            <Animatable.View ref={(comp)=>{this.userValidate=comp}}>

            <Fumi iconClass={Icon} iconName={"lock"} iconSize={24} style={styles.inputkey}
                  onChangeText={(text)=>this.setState({activateSimple:text})}
            />
            </Animatable.View>
            <Button style={styles.btnActive}
                    isLoading={this.state.userSimpleLoading}
                    textStyle={styles.btnTextActive}
                    onPress={()=>this.tryToActiveGeolocated()}
            >{text}</Button>

        </View>)
    }
tryToActiveGeolocated()
{
    const {activateSimple,user}=this.state;
    this.setState({userSimpleLoading:true});
    if(user.validation_code===String(activateSimple)){
     valifateAgent(user,null).then((result)=>{
            console.log(result)
            if(result.success===1){
                let us={}

                for(let key in user){
                    const val=user[key];
                    if(key!=='active')us['active']='oui';
                    us[key]=val;
                }
                saveNewuser(us);
                setTimeout(() => {
                    this.gotoHome()
                }, 1000)
            }else{
                console.log(result.message)
                this.userValidate.shake(800)
            }
            this.setState({userSimpleLoading:false});
        }).catch((e)=>{
            console.log(e)
            this.setState({userSimpleLoading:false});
            this.userValidate.shake(800)
        })

    }else{
        setTimeout(()=>{
            this.setState({userSimpleLoading:false});
            this.userValidate.shake(800)
        },2000)
    }
}

    tryToActivateHypervisor() {
        const {activateSimple,user,nbre_code,nbre_code_superviseur}=this.state;
        this.setState({userSimpleLoading:true});
        if(user.validation_code===activateSimple){
            valifateAgent(user,{nbre_code:nbre_code,nbre_code_superviseur:nbre_code_superviseur})
                .then((result)=>{
                if(result.success===1){
                    let usr={}
                    usr['etat']=1
                    for(key in user){
                        console.log(usr)
                      if(key!=='etat')usr[key]=user[key]

                    }
                    saveNewuser(usr);
                    setTimeout(() => {
                        this.gotoHome()
                    }, 1000)
                }else{
                    console.log(result.message)
                    this.userValidate.shake(800)
                }
                this.setState({userSimpleLoading:false});
            }).catch((e)=>{
                this.setState({userSimpleLoading:false});
                this.userValidate.shake(800)
            })

        }else{
            setTimeout(()=>{
                this.setState({userSimpleLoading:false});
                this.userValidate.shake(800)
            },2000)
        }
    }

    renderHypervisorActivation() {
        const text=I18n.t('ACTIVATE_ACCOUNT')

        return (<View style={{
            backgroundColor:this.type===1?theme.primaryDarkAdvanced:theme.primary,
            flex:1,
            justifyContent:'center',
            alignItems:'center',
        }}>
            <View style={{flexDirection:'row',alignItems:'center',justifyContent:'center'}}>
            <Image style={{width:responsiveWidth(90),resizeMode: 'contain',}} source={require('./../../datas/img/icon3.png')}/>

            </View>
            <Text style={styles.titleText}>Derniere étape</Text>
            <Text style={styles.descriptionText}>{I18n.t('SUBTITLE_ACTIVE_ACCOUNT')}</Text>

            <Animatable.View ref={(comp)=>{this.userValidate=comp}}>
            <Fumi iconClass={Icon} iconName={"lock"}
                  onChangeText={(text)=>this.setState({activateSimple:text})}
                  iconSize={24} style={styles.inputkey}/>
            </Animatable.View>
            <View style={{flexDirection:"row",alignItems:'center',justifyContent:'space-evenly'}}>
                <View style={{width:responsiveWidth(45)}}>
                    <Text style={{color:"white"}}>{I18n.t('SUPERVISOR_NUMBER')}</Text>
                    <Fumi iconClass={Icon}
                          iconName={"people"} iconSize={24} style={styles.inputkey2}
                          onChangeText={(text)=>{this.setState({nbre_code_superviseur:text})}}
                    />
                </View>
                <View style={{width:responsiveWidth(45)}}>
                    <Text style={{color:"white"}}>{I18n.t('GEOLOCATED_NUMBER')}</Text>
                <Fumi iconClass={Icon} iconName={"group"}
                      iconSize={24} style={styles.inputkey2}
                      onChangeText={(text)=>this.setState({nbre_code:text})}
                />
                </View>
            </View>
            <Button style={styles.btnActive}
                    textStyle={styles.btnTextActive}
                    isLoading={this.state.userSimpleLoading}

                    onPress={()=>this.tryToActivateHypervisor()}
            >{text}</Button>
        </View>)
    }

}
const styles=StyleSheet.create({
    container:{

    },
    titleText:{
        color:'white',
        fontSize:20,
        fontWeight:'bold',
        marginBottom:20
    },
    titleText2:{
        color:'white',
        fontSize:20,
        alignSelf:'center',
        fontWeight:'bold',
        marginBottom:20
    },
    descriptionText:{
    color:'white',
        fontSize:16,
        marginLeft:responsiveWidth(7),
        marginRight:responsiveWidth(7),
        textAlign:'center',
    marginBottom:20
    },
    btnTextActive:{
      fontSize:17,
      fontWeight:'bold',
      color:'white'
    },
    inputkey2:{
        width:responsiveWidth(40),
        height:70,alignSelf:'center',borderRadius:6,marginBottom:responsiveHeight(5)
    },
    inputkey:{
        height:70,width:responsiveWidth(90),alignSelf:'center',borderRadius:6,marginBottom:responsiveHeight(5)},
    btnActive:{
        borderColor:'transparent',
        width:responsiveWidth(90),
        alignSelf:'center',
        backgroundColor:theme.accent,
    }
})