const ContractForm = {
    templateUrl : 'js/app/components/contract/contract-form.html',
    create : function( props )
    {
        var app = this.app,
            cd = props.get( 'contract'),
            profileId = props.get( 'profileId' ),
            members = props.get( 'members' ),
            groupId = props.get( 'groupId' ),
            $container = $( this.container ),
            Countries = app.classManager.get( 'Countries' );

        this.render(
            {
                cd: cd,
                profileId : profileId,
                groupId : groupId,
                group : app.user.getActiveGroup(),
                members : members,
                Countries : Countries
            }
        );

        $container.find( '[name="type"]' ).change( function()
        {
            if ( 'flatrate' === $( this ).val() )
            {
                $container.find( '[name="max_price_factor"]' ).attr( 'disabled', true );
            }
            else
            {
                $container.find( '[name="max_price_factor"]' ).attr( 'disabled', false );
            }
        });

        $container.find( '[name="profile_id"]' ).change( function()
        {
            let m = null;
            for ( let mi = 0; mi < members.length; mi++ )
            {
                if ( members[ mi ].get( 'id' ) == $(this).val() )
                {
                    m = members[ mi ];
                    break;
                }
            }

            if ( m )
            {
                $container.find( '[name="street"]' ).first().val( m.get( 'street', '' ) );
                $container.find( '[name="zip_code"]' ).first().val( m.get( 'zip_code', '' ) );
                $container.find( '[name="city"]' ).first().val( m.get( 'city', '' ) );
            }
        });

        $container.find( '[name="profile_id"]' ).trigger( 'change' );
    },

    isValid : function()
    {
        const $container = $( this.container ),
              app = this.app,
              $form = $container.find( '[data-id="contract-form"]' ).first();

        let isValid = this.app.util.Form.bootstrapValidate( $form );

        if ( $form.find( '[name="type"]:checked' ).val() === 'quota' &&
             +($form.find( '[name="maxPriceFactor"]' ).val()) <= 0 )
        {
            app.UI.toastError( 'Bitte geben Sie einen Wert für den Abrechnungsfaktor ein.' );
            isValid = false;
        }

        return isValid;
    },

    getFormProperties : function()
    {
        let arr = this.getForm().serializeArray(),
            props = {};

        for ( let i = 0; i < arr.length; i++ )
        {
            props[ arr[ i ].name ] = arr[ i ].value;
        }

        return props;
    },

    getForm : function()
    {
        return $( this.container ).find( '[data-id="contract-form"]' ).first();
    },

    destroy : function()
    {

    }
};

export { ContractForm };