﻿ModulePoolDetails.CompositionModule = ModulePoolDetails.CompositionModule || (function () {
    //args:
    //  panelID
    //  vueID

    var _args = {};

    return {
        init: function (args) {
            _args = $.extend({
            }, args);
        },
        start: function () {
            $("#" + _args.panelID + " ." + Static.VueTabInfoClass).basicTabs();

            var jsonData = JSON.parse(Func.getPanelJsonData(_args.panelID));
            
            var mappingOptions = {
                'Compositions': {
                    create: function (options) {
                        var composition = ko.mapping.fromJS(options.data);
                        composition.selectedIntervenant = ko.observable()
                        composition.selectedIntervenant.subscribe(function (v) {
                            if (v) {
                                composition.IntervenantID(v.value);
                                composition.IntervenantLibelle(v.description);
                            }
                        });
                       
                        return composition;
                    }
                }
            }

            var factory = (function () {
                var id = 0;

                var composition = function (id, poolID) {
                    var self = this;

                    self.ID = ko.observable(id);
                    self.PoolID = ko.observable(poolID);
                    self.IntervenantLibelle = ko.observable('');
                    self.IntervenantID = ko.observable(null);
                    self.DateEntree = ko.observable('');
                    self.DateSortie = ko.observable('');
                    self.Commentaire = ko.observable('');
                    self.Archive = ko.observable(false);

                    self.selectedIntervenant = ko.observable()
                    self.selectedIntervenant.subscribe(function (v) {
                        if (v) {
                            self.IntervenantID(v.value);
                            self.IntervenantLibelle(v.description);
                        }
                    });
                };

                return {
                    createComposition: function (poolID) {
                        return new composition(--id, poolID);
                    }
                }
            }());

           

            var entityViewModel = function () {
                var self = this;
                self.vueID = _args.vueID;
                self.panelID = _args.panelID;
                self.data = ko.mapping.fromJS(jsonData, mappingOptions);
                self.changeTracker = new ko.ChangeTracker(self.data, true);

                self.addComposition = function () {
                    self.data.Compositions.unshift(factory.createComposition(self.data.PoolID()));
                };
               
                self.removeComposition = function (data) {
                    self.data.Compositions.remove(data);
                }
                
                //self.compositions = ko.computed(function () {
                //    var data = ko.observableArray(self.data.Compositions());
                //    return data.sort(function (left, right) {
                //        return left.ID() === right.ID() ? 0 : (left.ID() < right.ID() ? -1 : 1);
                //    });
                //});

                self.save = function () {
                    Func.post({
                        urlCode: "POOL_COMPOSITION_SAVE",
                        data: ko.mapping.toJSON(self.data),
                        panelID: self.panelID,
                        reloadPanel: true,
                        doneCallback: function (data, textStatus, jqXHR) {
                        },
                        failCallback: function (jqXHR, textStatus, errorThrown) {
                            if (jqXHR.status === 409) {
                                Func.HandleConflict(self.panelID, ko.mapping.toJSON(self.data), Func.getUrl("POOL_DETAILS", { id: self.data.Pool.ID(), vueID: self.vueID }), Resources.GroupeVue.PoolDetails);
                            }
                        }
                    });
                };

                self.cancel = function () {
                    Func.cancelPanel(self.panelID);
                };

            }

            var viewModel = function () {
                var self = this;
                self.vueID = _args.vueID;
                self.panelID = _args.panelID;
                self.entity = new entityViewModel();
                self.isModeConflict = Func.getTabType(self.panelID) === Enums.TypeTab.Conflict;

                self.showArchives = ko.observable(false);
                self.toggleArchivesView = function () {
                    self.showArchives(!self.showArchives());
                }

                self.compositionAutoCompleteItems = ko.observableArray();

                self.getCompositionAutoCompleteItems = function (searchTerm, sourceArray) {
                    Func.getAutoComplete('INTERVENANT', self.vueID, '', searchTerm, function (data) {
                        sourceArray(data.map(function (item) {
                            return new Types.AutoCompleteItem(item.ID, item.Libelle, item.Description);
                        }));
                    });
                }

                //Abonnement aux actions générales
                Vars.PostboxSubscriptions.push(new Types.PostboxSubscription(self.panelID,
                    ko.postbox.subscribe(Enums.PostboxNotifiers.ActionGeneralExecution, function (data) {
                        if (Vars.CurrentVue.vueID == self.vueID && Vars.CurrentVue.panelID == self.panelID) {
                            switch (data.typeActionID) {
                                case (Resources.TypeAction.Save):
                                    self.entity.save();
                                    break;
                                case (Resources.TypeAction.Cancel):
                                    self.entity.cancel();
                                    break;
                                case (Resources.TypeAction.Export):
                                    self.entity.export();
                                    break;
                                default:
                                    Utils.consoleLog('ModulePoolDetails.InfosGeneralesModule : Action "' + data.typeActionID + '" indéfinie');
                            }
                        }
                    })
                    )
               );
            }
            var vm = new viewModel();

            ko.applyBindings(vm, document.getElementById(vm.panelID));

            if (vm.isModeConflict) {
                var serverJsonData = JSON.parse($("#" + vm.panelID).find("." + Static.ScriptServerDataClass).html());
                Utils.copyJsToKO(serverJsonData, vm.entity.data);
            }
        }
    };
}());