import {IAdminForm} from '../interfaces/components/IAdminForm';
import {TUser} from '../types/TUser';
import {IAppCommands} from '../interfaces/commands/IAppCommands';
import {TSettings} from '../types/TSettings';

declare let settings:TSettings;

export class AdminForm implements IAdminForm {

    protected container:HTMLElement;

    protected emailInput:HTMLInputElement;

    protected emailError:HTMLElement;

    protected passwordInput:HTMLInputElement;

    protected passwordError:HTMLElement;

    protected passwordConfirmInput:HTMLInputElement;

    protected data:TUser;

    protected appCommands:IAppCommands;

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

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

    protected eventsListen(): void
    {
        this.emailInput.oninput = (e:Event)=>{
            this.data.email = <string>this.emailInput.value;
        };
        this.passwordInput.oninput = (e:Event)=>{
            this.data.password = <string>this.passwordInput.value;
        };
        this.container.onsubmit = (e:Event)=>{
            e.preventDefault();

            if(this.passwordInput.value != this.passwordConfirmInput.value){
                this.passwordError.innerText = 'Пароли не совпадают.';
                return;
            }

            this.appCommands.request(this.data)
                .then((resp:any)=>{
                    if(resp.success){
                        window.location.href = settings.successUrl;
                    }else{
                        this.showErrors(resp.errors);
                    }
                },
                (resp:any)=>{
                    this.showErrors(resp.errors || {});
                });
        };
    }

    public loadData(data:TUser): void
    {
        this.data = data;
        this.emailInput.value = data.email;
    }

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

}