angular.module('app').service('ManageViewsService', function(SQConstants) {

    this.getViewXML = function(view){
        var xmlDoc = document.implementation.createDocument(null, "View");
        var xmlObj = $(xmlDoc);

        var dbViewObj = xmlObj.find('View')[0];
        dbViewObj.setAttribute("name", view.name);
        dbViewObj.setAttribute("originalName", view.originalName);

        var columnsObj = xmlDoc.createElement('Columns');
        dbViewObj.appendChild(columnsObj);

        for (var i = 0; i < view.columns.length; i++) {
            var column = view.columns[i];

            var columnObj = instance.createColumnObj(column);
            columnsObj.appendChild(columnObj);
        }

        return new XMLSerializer().serializeToString(dbViewObj);
    }
    
    this.createColumnObj = function(column) {
        var xmlDoc = document.implementation.createDocument(null, "View");

        var columnObj = xmlDoc.createElement('Column');
        columnObj.setAttribute("class", column.class);
        columnObj.setAttribute("name", column.columnName);

        columnObj.setAttribute("sampleType", valueFilled(column.sampleType) ? column.sampleType : instance.sampleTypes.full);
        columnObj.setAttribute("direction", valueFilled(column.direction) ? column.direction : instance.directions.both);
        columnObj.setAttribute("plType", valueFilled(column.plType) ? column.plType : instance.plTypes.money);
        columnObj.setAttribute("resultType", valueFilled(column.resultType) ? column.resultType : instance.resultTypes.main);

        columnObj.setAttribute("confidenceLevel", valueFilled(column.confidenceLevel) ? column.confidenceLevel : "0");
        columnObj.setAttribute("market", valueFilled(column.market) ? column.market : "0");
        columnObj.setAttribute("subresult", valueFilled(column.subresult) ? column.subresult : "0");
        columnObj.setAttribute("showMainResult", valueFilled(column.showMainResult) ? column.showMainResult : true);

        return columnObj;
    }

    var instance = this;

    this.sampleTypes = SQConstants.getConstants().sampleTypes;
    this.directions = SQConstants.getConstants().directions;
    this.plTypes = SQConstants.getConstants().plTypes;
    this.resultTypes = SQConstants.getConstants().resultTypes;
    this.resultTypesList = SQConstants.getConstants().resultTypesList;
    
});