/*xiaoqing 2012.11.11*/
function SoapAction() {
    // jQuery.support.cors = true;
}
SoapAction.prototype.getData = function (soap) {
    soap.body = this.createBody(soap.body);
    var _this = this;
    $.ajax({
        url:soap.url,
        type:"post",
        data:soap.body,
        dataType:"text",
        contentType:"text/xml; charset=utf-8",
        headers:{SOAPAction:'"http://opcfoundation.org/webservices/XMLDA/1.0/' + soap.name + '"'},
        success:function (data) {
            data = _this.clearXml(data);
            soap.success(data);
        },
        error:function () {
            soap.error();
        }
    });
};

SoapAction.prototype.clearXml = function (data) {
    var reg_xml_header = /<\?xml.*?\?>/g;
    data = data.replace(reg_xml_header, "");
    var xmlns = /xmlns\:[^=]*/g;
    var ns = data.match(xmlns) || [];
    for (var i = 0, l = ns.length; i < l; i++) {
        var name = ns[i].split(":")[1];
        var reg_name = new RegExp(name + ":", "g");
        data = data.replace(reg_name, "");
    }
    var xml = "<xml>" + data + "</xml>";
    return $.parseXML(xml);
};
SoapAction.prototype.createBody = function (body) {
    var return_val =
        '<?xml version="1.0" encoding="utf-8"?>' +
            '<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">' +
            '<soap:Body>' + body + ' </soap:Body>' +
            '</soap:Envelope>';
    return return_val;
};

SoapAction.prototype.getRoot = function (getItemsUrl, callback) {
    var _this = this;
    $.get(getItemsUrl, {/*_t:new Date().getTime()*/}, function (result) {
        result = _this.clearXml(result);
        var Servers = [];

        $(result).find("Server").each(function () {
            var Server = $(this),
                ProgID = Server.attr("ProgID"),
                server_obj = {
                    id:ProgID,
                    uid:Server.attr("ID"),
                    groups:[]
                };

            Server.find("Group").each(function(){
                var Group = $(this),
                     GroupName = Group.attr("Name"),
                    group_obj = {
                        id:GroupName,
                        uid:Group.attr("ID"),
                        items:[]
                    };

                Group.find("Item").each(function(){
                    var Item = $(this),
                        ItemID = Item.attr("ItemID");
                        
                           
              var   item_obj = {
                            id:ItemID,
                            uid:Item.attr("ID"),
                            desc:Item.attr("Description")
                        };
                    group_obj.items.push(item_obj);
                });
                server_obj.groups.push(group_obj);
            });
            Servers.push(server_obj);
        });
        callback(Servers, result);
    }, "text");
};

SoapAction.prototype.read = function (data, callback) {
    var itemNames = data.items;
    var group_uid = data.group_uid;
    if (!itemNames || !itemNames.length) {
        return;
    }
    callback = callback || $.noop;
    var body =
        '<Read xmlns="http://opcfoundation.org/webservices/XMLDA/1.0/">' +
            '<Options ReturnItemTime="true" ReturnItemName="true" ClientRequestHandle="" LocaleID="en-US" />' +
            '<ItemList>';

    var itemNamesObj = {};
    for(var i=0;i<itemNames.length;i++){
        body += '<Items ItemName="' + itemNames[i].id + '"' +
            ' ClientItemHandle="'+itemNames[i].uid+'" ClientRequestHandle="'+group_uid+'"/>';
        itemNamesObj[itemNames[i].id] = {
            desc:itemNames[i].desc,
            ReType:itemNames[i].ReType,
            Address:itemNames[i].Address
        }
    }

    body += '</ItemList></Read>';
    var soap = {
        // url:"http://localhost:8085/Read",
        url:"/soap/Read",
        name:"Read",
        body:body,
        success:function (data) {
            var response = $(data).find(this.name + "Response"),
                itemList = response.find("RItemList"),
                items = itemList.find("Items");
            var arr = [];
            items.each(function (index, val) {
                var item = $(this);
                var item_name = item.attr("ItemName");
                if (!item_name) {
                    return;
                }
                var tempObj = itemNamesObj[item.attr("ItemName")];
                var soapObj = {
                    itemName:item.attr("ItemName"),
                    valueType:item.find("Value").attr("type") || "",
                    value:item.find("Value").text(),
                    //quality:item.find("Quality").text(),
                    //timestamp:dateFormat(item.attr("Timestamp")),
                    time:item.attr("Timestamp") || "",
                    quality:item.find("Quality").attr("QualityField") || "",
                    desc:tempObj.desc
                };
                arr.push(soapObj);
            });
            callback(arr, group_uid,  response);

        },
        error:function () {

        }
    };
    this.getData(soap);
};

SoapAction.prototype.write = function (items) {
    items = items || [
        {name:"Channel_1.Device_1.Tag_1", value:1}
    ];
    if (!$.isArray(items)) {
        items = [items];
    }

    var body =
        '<Write xmlns="http://opcfoundation.org/webservices/XMLDA/1.0/">' +
            '<ItemList>';
    for (var i = 0, l = items.length; i < l; i++) {
        body += '<Items   ItemName="' + items[i].name + '" ' +
            'ClientItemHandle="'+items[i].uid+'" ClientRequestHandle="'+items[i].group_uid+'">' +
            '<DiagnosticInfo>string</DiagnosticInfo>' +
            '<Value>' + items[i].value + '</Value>' +
            '<Quality/></Items>';
    }
    body += '</ItemList></Write>';
    var soap = {
        url:"/soap/Write",
        name:"Write",
        body:body,
        success:function (data) {
            //  alert(data)
            var response = $(data).find(this.name + "Response"),
                itemList = response.find("RItemList"),
                items = itemList.find("Items");

        },
        error:function () {
        }
    };
    this.getData(soap);

};

SoapAction.prototype.getStatus = function(callback) {
    callback = callback || $.noop;
    var body =
        ' <GetStatus LocaleID="en-US" xmlns="http://opcfoundation.org/webservices/XMLDA/1.0/" />';
    var soap = {
        url:"GetStatus",
        name:"GetStatus",
        body:body,
        success:function (data) {
            var response = $(data).find("GetStatusResult");
            var state = response.attr("ServerState");
            $("#getStatus").html(state);
            if (state == "running") {
                callback(state);
            }else{
                if(window.console) console.log(state);
            }
        },
        error:function () {
            if(window.console) console.log("getStatus error!!!");
        }
    };
    this.getData(soap);
};

