var app = {
    Cookie: {
        Read: function (c_name) {
            if (document.cookie.length > 0) {
                var c_start = document.cookie.indexOf(c_name + "=");
                if (c_start != -1) {
                    c_start = c_start + c_name.length + 1;
                    var c_end = document.cookie.indexOf(";", c_start);
                    if (c_end == -1) {
                        c_end = document.cookie.length;
                    }
                    return unescape(document.cookie.substring(c_start, c_end));
                }
            }
            return "";
        },
        Write: function (name, value, days, directory) {
            var expires;
            var date = new Date();
            if (days) {
                date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
                expires = "; expires=" + date.toGMTString();
            }
            else {
                date.setTime(date.getTime() + (1 * 24 * 60 * 1000));
                expires = "; expires=" + date.toGMTString();
            }
            document.cookie = name + "=" + value + expires + (directory != undefined ? ";path=/" + directory : ";path=/");
            // document.cookie = name + "=" + value + expires + directory != undefined ? ";path=/" + directory : ";path=/";
        },
        Remove: function (name) {
            this.Write(name, "", "1950-01-01");
        },
    },
    LocalStorage: {
        Read: function (name) {
            var lname = name.toLowerCase();
            return typeof (window.localStorage.getItem(lname)) == "string" ? window.localStorage.getItem(lname) : JSON.stringify(window.localStorage.getItem(lname));
        },
        Write: function (name, dataStr) {
            return window.localStorage.setItem(name.toLowerCase(), dataStr);
        },
        Remove: function (name) {
            return window.localStorage.removeItem(name.toLowerCase());
        }
    },
    box: {
        msg: {
            text: ko.observable(),
            show: ko.pureComputed({
                read: function () {
                    return app.box.msg.text() == undefined ? false : true;
                },
                write: function (value) {
                    return app.box.msg.text(undefined)
                }
            })
        },
        confirm: {
            message: ko.observable(),
            callback: confirm || function () {
                console.log("asdas");
            }
        }
    }
};

function multiplePaymentModel(_type, _price) {

    var t = this;

    t.Type = ko.observable();

    t.Price = ko.observable(_price);

    t.Price.subscribe(function (val) {
        var _val = (typeof (val) == "number" ? val.toString() : val);
        if (_val.indexOf(",") !== -1) {
            t.Price(parseFloat(val.replace(/,/g, '.')));
        }
    })

    t.SubType = ko.observable(_type);

    t.SubTypes = ko.observableArray();
}

function customerModel(_Code, _RoomNo, _FirstName, _LastName) {
    var t = this;

    t.Code = ko.observable(_Code);

    t.RoomNo = ko.observable(_RoomNo);

    t.FirstName = ko.observable(_FirstName);

    t.LastName = ko.observable(_LastName);

}



//function GetFormData(e) {
//    var Result = {
//        Errors: {
//            name: [],
//            size:[]
//        },
//        FormData: null
//    }
//    var files = e.files;
//    for (var i = 0; i < files.length; i++) {
//        var file = e.files[i],
//            nameResult = CheckFileName(file.name),
//            sizeResult = FileSizeControl(file);
//        if (!sizeResult.success) {
//            Errors.size.push({ "fileName": file.name, "size": sizeResult.size });
//        }
//        if (!nameResult) {
//            Errors.name.push({ "fileName": file.name });
//        }
//    }   
//    var imageType = /image.*/;
//    var form_data = new FormData();
//    for (var i = 0; i < files.length; i++) {
//        if (!files[i].type.match(imageType)) return;
//        form_data.append('file' + i, files[i]);
//    }
//    result.FormData = form_data;
//    return Result;
//};

//function FileSizeControl(file) {
//    var Result = {
//            success: false,
//            size: 0
//        },
//        kb = file.size / 1024,
//        mb = parseFloat(kb / 1024).toFixed(2);

//    if (mb < 0.5) {
//        Result.success = true;
//        Result.size = mb || "0";
//    } else {
//        Result.success = false;
//        Result.size = mb || "0";
//    }
//    return Result;
//}

//function CheckFileName(filename) {
//    var ext = GetExtension(filename);
//    switch (ext.toLowerCase()) {
//        case 'jpg':
//        case 'jpeg':
//        case 'gif':
//        case 'bmp':
//        case 'png':
//        case 'bmp':
//        case 'tif':
//            //etc
//            return true;
//    }
//    return false;
//}

//function GetExtension(filename) {
//    var parts = filename.split('.');
//    return parts[parts.length - 1];
//}

//function FileUpload(url, formData, successCallback) {
//    $.ajax({
//        url: url,
//        cache: false,
//        contentType: false,
//        processData: false,
//        data: formData,
//        type: 'POST',
//        success: successCallback,
//        error: function (error) {
//            console.log(error);
//        }
//    });
//}

function EditViewModel(_Id, _Name, _File, _Files, _Heat, _Interval, _CookingTime, _Description, _Calori) {

    var t = this;

    t.Id = ko.observable(_Id);

    t.Name = ko.observable(_Name);

    t.File = ko.observable(_File);/*.extend({ required: { message : "Bu alan zorunludur!" }});*/

    // t.Files = ko.observableArray(_Files || []);

    t.Heat = ko.observable(_Heat);

    t.Interval = ko.observable(_Interval);

    t.CookingTime = ko.observable(_CookingTime);

    t.Description = ko.observable(_Description).extend({ required: { message: "Bu alan zorunludur!" } });;

    t.Calori = ko.observable(_Calori);

    t.errors = ko.validation.group(t, { deep: true });

    t.SaveChanges = function () {
        if (t.errors().length > 0) {
            t.errors.showAllMessages();
        } else {
            var data = JSON.stringify(ko.mapping.toJS(view.ProductDetail()));
            PostQuery("/api/AddDetail", { "data": data }, function (res) {
                if (res.Error) {

                } else {
                    if (view.ProductDetails().Details) {
                        view.ProductDetails().Details.Calori(t.Calori());
                        view.ProductDetails().Details.CookingTime(t.CookingTime());
                        view.ProductDetails().Details.Description(t.Description());
                        view.ProductDetails().Details.Interval(t.Interval());
                        view.ProductDetails().Details.Heat(t.Heat());
                        view.ProductDetails().Details.ImgPath(t.File());
                        app.LocalStorage.Remove("Alldata")
                        app.LocalStorage.Write("AllData", view.data());
                    }
                    view.Next("product-edit", "container", undefined, function () { return view.ProductDetail(undefined); });
                }
            })
        }
    }
}




function detailModel(image, ingredients) {
    var t = this;

    t.ingredients = ko.observable(ingredients);
    t.images = ko.observable(image);
}


function settingsModel(_ID, _Name, _Price, _Quantity, _LastValue) {
    var t = this;

    t.ID = ko.observable(_ID);

    t.Name = ko.observable(_Name);

    t.Price = ko.observable(_Price);

    t.Quantity = ko.observable(_Quantity);

    t.Extras = ko.observableArray();

    t.DisplayPrice = ko.pureComputed(function () {
        var price = + (t.Price() * t.Quantity());
        return price;
    })

    t.LastValue = ko.observable(-_LastValue);
}

function cart(data) {

    var t = this;

    t.ID = ko.observable(data && data.ID);

    t.Name = ko.observable(data && data.Name);

    t.Price = ko.observable(data && data.Price);

    t.Quantity = ko.observable(data && data.Quantity);

    t.Extras = ko.observableArray();

    t.ExtrasKey = ko.pureComputed(function () {
        return JSON.stringify(ko.toJS(t.Extras));
    });

    t.isOk = ko.observable();

    //t.DisplayPrice = ko.pureComputed(function () {
    //    var price = + (t.Price() * t.Quantity());
    //    return price;
    //})


    if (data.Extras && data.Extras.length > 0) {
        for (var i = 0; i < data.Extras.length; i++) {
            // if'in içinde  || data.Extras[i].ExtraCount == -1 şartı da vardı. Çıkarılan ek özelliklerde fiyat düşmemesi için kaldırdım.
            if (data.Extras[i].ExtraCount == 1) {
                var calcPrice = (parseFloat(data.Extras[i].Price || 0) * parseFloat(data.Extras[i].ExtraCount));
                t.Extras().push(new extraProductModel(calcPrice, data.Extras[i].Name, data.Extras[i].isOk, data.Extras[i].ID, data.Extras[i].ExtraCount));
            }
            if (data.Extras[i].ExtraCount == -1) {
                t.Extras().push(new extraProductModel(0, data.Extras[i].Name, data.Extras[i].isOk, data.Extras[i].ID, data.Extras[i].ExtraCount));
            }
        }
    }

    t.DisplayPrice = ko.pureComputed(function () {
        var extra = 0;
        t.Extras().map(function (obj) {
            extra += obj.Price();
        })
        var price = + ((parseFloat(t.Price()) + extra) * t.Quantity());
        return price;
    })

    t.AfterAdd = ko.observable(false);

    t.Query = ko.observable();

    t.AccNo = ko.observable(data && data.AccNo);
    t.Currency = ko.observable(data && data.Currency);
}

function extraProductModel(price, name, isOk, ID, count) {
    var t = this;
    t.ID = ko.observable(ID);
    t.Price = ko.observable(price);
    t.Name = ko.observable(name);
    t.isOk = ko.observable(isOk);
    t.extraCount = ko.observable(count || 1);
}
function userModel(model) {

    var t = this;

    //if (app.Cookie.Read("BL") === "") {
    //    userInfo = undefined;
    //} else {
    //    userInfo = JSON.parse(app.Cookie.Read("BL"));
    //} // eski version
    var userInfo = model;

    t.ID = ko.observable(userInfo && userInfo.ID);

    t.UserName = ko.observable(userInfo && userInfo.UserName);

    t.Password = ko.observable(userInfo && userInfo.Password).extend({ required: { message: "Boş geçilemez!" }, maxLength: { params: 20, message: "En fazla 20 karekter girebilirsiniz!" } });

    t.RememberMe = ko.observable(false);

    t.DepartNo = ko.observable(userInfo && userInfo.DepartNo).extend({ required: { message: "Departman Seçiniz!" }, maxLength: { params: 20, message: "En fazla 20 karekter girebilirsiniz!" } });

    t.errors = ko.validation.group(t, { deep: true });

    t.NotFound = ko.observable(false);

    t.ErrorMessage = ko.observable();

    t.RoleId = ko.observable(userInfo && userInfo.RoleId);

    t.RoleName = ko.observable(userInfo && userInfo.RoleName);

    t.Roles = ko.observableArray(userInfo && ko.mapping.fromJS(userInfo.Roles)() || []);
   
    t.SignalRId = ko.observable();

    t.Login = function (successCallback) {
        if (t.errors().length > 0) {
            t.errors.showAllMessages();
        } else {
            PostQuery("/api/Login", { departmanCode: t.DepartNo(), password: t.Password() }, successCallback || function (response) {
                if (response.Error) {
                    t.NotFound(true);
                    t.ErrorMessage(response.Error);
                } else if (response.user) {
                    t.ID(response.user.ID);
                    t.UserName(response.user.UserName);
                    t.RoleId(response.user.RoleId);
                    if (response.roles.length > 0) {
                        var roles = response.roles.filter(function (r) {
                            return r.UseRole == true;
                        });
                        if (response.roles.length == roles.length) {
                            response.roles.push({ RoleId: 6, Name: "CanEdit", UseRole: true });
                        }
                        t.Roles(response.roles);
                    }
                    t.LoginControl(ko.toJS(t));
                    //app.Cookie.Write("AU", JSON.stringify(ko.toJS(t)), 1);
                    //app.Cookie.Write("BL", JSON.stringify(ko.toJS(t)), t.RememberMe() == true ? 30 : 1);
                    app.LocalStorage.Write("AU", JSON.stringify(ko.toJS(t)));
                    app.LocalStorage.Write("BL", JSON.stringify(ko.toJS(t)));

                    //view.Run();
                    location.reload();
                }
            })

        }
    }

    t.RoleObject = ko.pureComputed(function () {
        var roles = ko.toJS(t.Roles());
        if (roles.length == 0) {
            return {};
        } else {
            return roles.reduce(function (arr, item, i) {
                arr[item.Name] = item.UseRole; return arr
            }, {})
        }
    })
}

