import React from 'react';
import Modularity from 'modularity-front';
import { Row, Col } from 'react-materialize';


import Button from '@material-ui/core/Button';

import Form from '../Modules/Form.js';
import UserService from '../Services/UserService.js';
import Dictionary from '../Services/DictionaryService.js';

import Toast from '../helpers/Toast';

import './UserPackage.css';

let Module = Modularity.Module;
class UserPackage extends Modularity.Module {
	constructor(props) {
		super(props);
		this.state = {
            registerForm: false
		}

        let propertiesService = {
            Token: (t) => {
                this.checkToken();
                this.Token.set(t);
                this.forceUpdate();
            },
            User: (u) => {
                this.User.set(u);
                this.forceUpdate();
            }
        }

        this.back_service = new UserService(propertiesService);
        // this.Token.onUpdate((v) => { this.back_service.Token.update(v);this.forceUpdate(); });

        let withLogin = this.LoginURL.value;
        if (withLogin) {
            this.RoutingSystem.addRoute(withLogin, this.RoutingSystem.currentView, 'PackageLogin')
        }
        
        var url = new URL(window.location.href);
        var confirmtoken = url.searchParams.get("token");
        if (confirmtoken) {
            this.back_service.confirmUser(confirmtoken)
            .then(() => Toast.success("Ο χρήστης επιβεβαιώθηκε. Συνδέσου τώρα!"))
        }
        setTimeout(() => this.checkToken(), 0);
        this.RoutingSystem.onRouteChange("Login", () => this.checkToken())
	}

    checkToken() {
        let withLogin = this.LoginURL.value;
        let route = this.RoutingSystem.getRoute().url;
        if (route === withLogin) {
            this.setState({
                login: true,
                ref: this.RoutingSystem.currentState.ref || "/home"
            });
            if(this.back_service.isLogged()) {
                this.CoreSystem.go(this.state.ref);
            }
        } else {
            this.setState({
                login: false
            });
        }
    }
    showLogin() {
        this.setState({
            login: true,
            ref: this.RoutingSystem.getRoute().url
        });
        this.CoreSystem.go("/login", { ref: this.RoutingSystem.getRoute().url });
    }

    login(data) {
        // check if all data is comple
        if (!data) return;
        let { username, password } = data;
        if (username && password)
            this.back_service.login(data).then((d) => {
                Toast.notify(Dictionary.get("Welcome") + " &nbsp;<b>" + username +"</b>");
                this.CoreSystem.go(this.state.ref);
            }).catch((err) => {
                if(err.status === 400) {
                    Toast.error(Dictionary.get("Wrong credentials"));
                } else if (err.status === 403) {
                    Toast.notify(Dictionary.get("A verification mail has been sent to your inbox. You need to verify before login."));
                }
            });
    }

    register(data) {
        // check if all data is comple
        if (!data) return;
        let { username, password, email } = data;
        if (username && password && email)
            this.back_service.register(data).then((user) => {
                Toast.success(Dictionary.get("Successfully registered! Please login"));
                this.setState({
                    registerForm: false
                })
            }).catch((err) => {
                if(err.status === 400) {
                    Toast.error(Dictionary.get("Wrong credentials"));
                }
            });
    }

    logout() {
        this.back_service.logout().then(() => {
            Toast.notify(Dictionary.get("Logged out"));
            //window.location.href = "/login";
            this.forceUpdate();
        }).catch(() => {
            Toast.error("Cannot Logout");
        });
    }

	render() {
        let Token = this.back_service.getToken() || 'missing';
        let User = this.back_service.User.value || {};

        // console.log("Token : ", Token);

        let FormInputs = {
            "username":{
                type:"text",
                placeholder:"Username",
                columns:12,
                filter: {
                    required: true
                }
            },
            "password":{
                type:"password",
                placeholder:"Password",
                columns:12,
                filter: {
                    required: true,
                    password: true
                }
            }
        }

        if (this.state.registerForm && this.withRegister.value) {
            FormInputs["email"] = {
                type:"email",
                placeholder:"Email",
                columns:12,
                filter: {
                    email: true,
                    required: true
                }
            }
        }
        
        let LoginScreen = <div className={'LoginScreen valign-wrapper'}>
                <div className={'FormContainer hoverable'}>
                    <Row>
                        <Col s={12}>
                            <img src={this.Logo.value || ''} />
                        </Col>
                        <Col s={12} className={'LoginText'}>
                            <h4>{this.Header.value || ''}</h4>
                        </Col>
                    </Row>
                    <Row>
                        <Col s={12}>
                            <Form key={Math.random()} className={'center-align'} FormInputs={FormInputs} 
                                  button={ this.state.registerForm ? Dictionary.get("Register") : Dictionary.get("Login") } onSubmit={(data) => this.state.registerForm ? this.register(data) : this.login(data)}
                                  activeButton
                                  />
                        </Col>
                        {this.withRegister.value ? 
                            <Col s={12} className={'RegisterText'} onClick={() => this.setState({registerForm: !this.state.registerForm})}>
                                {this.state.registerForm ? Dictionary.get("Already registered? Login now!") : Dictionary.get("You don't have an account? Register here!")}
                            </Col>
                        : ''}
                    </Row>
                </div>
                {super.render()}
            </div>;

        let needsLogin = Token === "missing";
        return  needsLogin ? ( this.state.login || this.ForceLogin.value ? LoginScreen : <Button className={this.className.value} onClick={() => this.showLogin()}>{Dictionary.get("Login")}</Button> )
            : 
            <div>
                <Button className={this.className.value} onClick={() => this.CoreSystem.go(this.UserURL.value)}>
                    {User.username || '...'}
                </Button>
                <Button className={this.className.value} onClick={() => this.logout()}>
                    {Dictionary.get("Logout")}
                </Button>
                {super.render()}
            </div>;
	}
}

UserPackage.Inputs = {
    ForceLogin: {
        type: Modularity.Module.Types.Boolean,
        defaultValue: false
    },
    withRegister: {
        type: Modularity.Module.Types.Boolean,
        defaultValue: true
    },
    LoginURL: {
        type: Modularity.Module.Types.Text,
        defaultValue: '/login'
    },
    Logo: {
        type: Modularity.Module.Types.Text,
        defaultValue: '/logo.png'
    },
    Header: {
        type: Modularity.Module.Types.Text,
        defaultValue: 'Tonersales'
    },
    UserURL: {
        type: Modularity.Module.Types.Text,
        defaultValue: '/user'
    },
    className: {
        type: Modularity.Module.Types.Text
    }
}

UserPackage.Outputs = {
    Token: {},
    User: {}
}

UserPackage.Category = "NikatlasPackages";
UserPackage.EditPosition = "top-center";
export default UserPackage;