﻿class AjaxifiedCarModelView extends ModelView
{
    // Attributes
    private _created: boolean = false;

    // Constructor
    constructor(parentEl: any, model: AjaxifiedCarModel, options?: TemplateViewOptions)
    {
        super(parentEl, model, options);
    }

    // Properties

    // Methods

    // Manually setup events
    BindEvents(): void
    {
        if (this._created) this.$(".submit-button").on("click", $.proxy(this.Update, this));
        else this.$(".submit-button").on("click", $.proxy(this.Create, this));
    }

    UnbindEvents(): void
    {
        this.$(".submit-button").off();
    }

    Create(e: JQueryEventObject): void
    {
        var model: AjaxifiedCarModel = <AjaxifiedCarModel>this.Model;
        model.Name = this.$(".car-name").val();
        model.Description = this.$(".car-description").val();
        this.Model.Create();
        e.preventDefault();
    }

    Update(e: JQueryEventObject): void
    {
        var model: AjaxifiedCarModel = <AjaxifiedCarModel>this.Model;
        model.Name = this.$(".car-name").val();
        model.Description = this.$(".car-description").val();
        this.Model.Update();
        e.preventDefault();
    }

    OnAjaxSuccess(modelStatus: ModelStatus): void
    {
        switch (modelStatus)
        {
            case ModelStatus.Created:
                window.alert("Created successfully");
                this._created = true;
                this.LoadTemplate("#update-car-template");
                this.Render();
                break;
            case ModelStatus.Read:
                this.Render();
                break;
            case ModelStatus.Updated:
                window.alert("Updated successfully");
                this.Render();
                break;
            case ModelStatus.Deleted:
                break;
        } 
    }
} 