import {ILoginForm} from '../interfaces/components/ILoginForm';
import {IAppCommands} from '../interfaces/commands/IAppCommands';
import {TErrors} from '../types/TErrors';
import {TSettings} from '../types/TSettings';

declare let settings:TSettings;

export class LoginForm implements ILoginForm {

    protected container:HTMLElement;

    protected form:HTMLElement;

    protected emailInput:HTMLInputElement;

    protected emailError:HTMLElement;

    protected passwordInput:HTMLInputElement;

    protected passwordError:HTMLElement;

    protected appCommands:IAppCommands;

    public setAppCommands(commands:IAppCommands)
    {
        this.appCommands = commands;
    }

    public init(container:HTMLElement)
    {
        this.container = container;
        this.form = this.container.querySelector('.js-form');
        this.emailInput = this.form.querySelector('.js-email-input');
        this.emailError = this.form.querySelector('.js-email-error');
        this.passwordInput = this.form.querySelector('.js-password-input');
        this.passwordError = this.form.querySelector('.js-password-error');
        this.eventsListen();
    }

    protected eventsListen()
    {
        this.form.onsubmit = (e:Event)=>{
            e.preventDefault();
            let email = this.emailInput.value;
            let password = this.passwordInput.value;
            this.appCommands.login(email, password)
                .then((resp:any)=>{
                    if(resp.success){
                        window.location.href = settings.successUrl;
                    }
                })
                .catch((reason:any)=>{
                    if(reason.errors){
                        this.showErrors(reason.errors);
                    }
                });
        };
    }

    protected showErrors(errors:TErrors)
    {
        if(errors['email']){
            this.emailError.innerText = errors['email'][0];
        }
        if(errors['password']){
            this.passwordError.innerText = errors['password'][0];
        }
    }

}