<template>
    <nb-container>
        <gradient-background :gradient="['#512DA8', '#673AB7']"></gradient-background>

        <nb-content>
            <nb-button
                class="login-link"
                full
                :onPress="() => this.props.navigation.navigate('Login')"
            >
                <nb-icon name="arrow-back"></nb-icon>
                <nb-text>Вернуться к авторизации</nb-text>
            </nb-button>

            <nb-form>
                <nb-grid class="image-picker-wrapper" :onPress="checkCameraPermission">
                    <nb-col class="image-preview">
                        <nb-thumbnail square v-if="userData.avatar !== null" class="picker-image" :source="userData.avatar"/>
                        <nb-icon v-if="userData.avatar === null" class="picker-icon" name="image"/>
                    </nb-col>

                    <nb-col class="desc">
                        <nb-text class="picker-text">Загрузите своё фото</nb-Text>
                        <nb-text class="picker-text" note :numberOfLines="1">Форматы: jpeg, png, bmp</nb-Text>
                    </nb-col>
                </nb-grid>

                <nb-content padder>
                    <nb-item>
                        <nb-icon class="input-icon" active name="person"/>

                        <nb-input
                            class="form-input"
                            v-model="userData.name"
                            placeholder="Имя"
                            placeholderTextColor="#fff"
                        />
                    </nb-item>

                    <nb-item>
                        <nb-icon class="input-icon" active name="log-in"/>

                        <nb-input
                            class="form-input"
                            v-model="userData.login"
                            placeholder="Логин"
                            placeholderTextColor="#fff"
                            auto-capitalize="none"
                        />
                    </nb-item>

                    <nb-item>
                        <nb-icon class="input-icon" active name="lock"/>

                        <nb-input
                            class="form-input"
                            v-model="userData.password"
                            placeholder="Пароль"
                            placeholderTextColor="#fff"
                            auto-capitalize="none"
                            :secure-text-entry="passwordMask"
                        />

                        <nb-icon
                            class="input-icon"
                            active
                            :name="(passwordMask) ? 'eye' : 'eye-off'"
                            :onPress="togglePasswordMask"
                        />
                    </nb-item>

                    <nb-item>
                        <nb-icon class="input-icon" active name="lock"/>

                        <nb-input
                            class="form-input"
                            v-model="userData.password_confirmation"
                            placeholder="Подтверждение пароля"
                            placeholderTextColor="#fff"
                            auto-capitalize="none"
                            secure-text-entry
                        />
                    </nb-item>
                </nb-content>
            </nb-form>

            <nb-content padder>
                <form-button
                    :gradient="['#a044ff', '#8c43ea']"
                    :waiting="loading"
                    :action="register"
                    title="Зарегистрироваться"
                />
            </nb-content>
        </nb-content>
    </nb-container>
</template>

<script>
    import * as ImagePicker from "expo-image-picker";

    import { Toast } from "native-base";

    import GradientBackground from "../../components/GradientBackground";
    import FormButton from "../../components/Form/FormButton";

    export default {
        name: 'Register',
        components: {
            GradientBackground,
            FormButton
        },
        props: {
            navigation: { type: Object }
        },
        data() {
            return {
                userData: {
                    name: '',
                    login: '',
                    password: '',
                    password_confirmation: '',
                    avatar: null
                },
                passwordMask: true,
                loading: false
            }
        },
        methods: {
            async checkCameraPermission() {
                let access = await ImagePicker.getCameraRollPermissionsAsync();
                console.log(access);
                if (access.status !== 'granted') {
                    Toast.show({
                        text: "Необходимо разрешение на чтение галереи!",
                        buttonText: "Закрыть",
                        type: "danger",
                        duration: 3000
                    });
                } else {
                    this.pickImage();
                }
            },
            async pickImage() {
                let image = await ImagePicker.launchImageLibraryAsync({
                    mediaTypes: ImagePicker.MediaTypeOptions.Images,
                    allowsEditing: true,
                    allowsMultipleSelection: false,
                    aspect: [4, 3],
                    quality: 1
                });
                console.log(this.image);

                if (!image.cancelled) {
                    let urlParts = image.uri.split('.'),
                        fileType = urlParts[urlParts.length - 1];

                    this.userData.avatar = {
                        uri: image.uri,
                        name: `photo.${fileType}`,
                        type: `photo/${fileType}`,
                    };

                    console.log(this.userData.avatar)
                }
            },
            async register() {
                this.loading = true;

                let formData = new FormData();
                formData.append('name', this.userData.name);
                formData.append('login', this.userData.login);
                formData.append('password', this.userData.password);
                formData.append('password_confirmation', this.userData.password_confirmation);
                formData.append('avatar', this.userData.avatar);

                let response = await this.$plugins.f('register', 'POST', formData);

                if (response.status) {
                    Toast.show({
                        text: "Регистрация успешно завершена",
                        buttonText: "ОК",
                        type: "success",
                        duration: 3000
                    });
                } else {
                    Toast.show({
                        text: "Произошла ошибка, проверьте правильность заполнения полей!",
                        buttonText: "Закрыть",
                        type: "danger",
                        duration: 3000
                    });
                }

                this.loading = false;
            },
            togglePasswordMask() {
                this.passwordMask = !this.passwordMask;
            },
        }
    }
</script>

<style scoped>
    .login-link {
        display: flex;
        justify-content: center;
        background-color: #673AB7;
    }

    .image-picker-wrapper {
        padding: 10px;
        display: flex;
        align-self: center;
    }

    .image-preview {
        width: 25%;
        justify-content: center;
        padding-left: 15px;
    }

    .picker-image {
        border-radius: 10px;
    }

    .picker-icon {
        font-size: 64px;
        color: #fff;
    }

    .desc {
        width: 75%;
        justify-content: center;
        border-bottom-width: 1px;
        border-bottom-color: #fff;
    }

    .picker-text {
        color: #fff;
    }

    .form-input {
        font-size: 18px;
        color: #fff;
        margin-top: 10px;
    }

    .input-icon {
        font-size: 26px;
        color: #fff;
        margin-top: 10px;
    }
</style>