var objCommon = WizCommonUI;
//
var scriptFileName = objCommon.GetScriptParamValue("ScriptFileName");
var databasePath = objCommon.GetScriptParamValue("DatabasePath");
//
var objDownloader = objCommon.CreateWizObject("WizKMControls.WizBatchDownloader");
//
var objDatabase = objCommon.CreateWizObject("WizKMCore.WizDatabase");
objDatabase.Open(databasePath);
//
var iniFileName = databasePath + "BlogDownloader.ini";
//
function formatInt(val) {
    if (val < 10)
        return "0" + val;
    else
        return "" + val;
}

function jsAlert(msg) {
    var objShell = objCommon.CreateActiveXObject("WScript.Shell");
    return objShell.Popup(msg, 10000, "Wiz", 0);
}
//
//
function getIni(section, key, def) {
    try {
        var val = objCommon.GetValueFromIni(iniFileName, section, key);
        if (val == null || val == "")
            return def;
        return val;
    }
    catch (err) {
        if (def == null)
            return "";
        return def;
    }
}

function extractFilePath(filename) {
    var pos = filename.lastIndexOf("\\");
    if (pos == -1)
        return filename;
    //
    return filename.substr(0, pos + 1);
}
function loadString(name) {
    var languageFileName = extractFilePath(scriptFileName) + "plugin.ini";
    //
    return objCommon.LoadStringFromFile(languageFileName, name);
}


function downloadCore(starred, count) {
    //
    var url;
    if (starred) {
        url = "https://www.google.com/reader/atom/user/-/state/com.google/starred";
    }
    else {
        url = "https://www.google.com/reader/atom/";
    }
    //
    url = url + "?n=" + count;
    //
    var xml = objCommon.URLDownloadToText(url);
    //
    var objXml = objCommon.CreateActiveXObject("MSXML.DOMDocument");
    objXml.async = false;
    if (!objXml.loadXML(xml)) {
        return null;
    }
    //
    return objXml;
}
//

function showBubbleMessage(title, msg) {
    var appPath = objCommon.GetScriptParamValue("AppPath");
    //
    var wizShellFileName = appPath + "WizShell.exe";
    var dllFileName = appPath + "WizTools.dll";
    //
    var params = "\"" + dllFileName + "\" WizToolsShowBubbleWindow2Ex /Title=" + title + " /LinkText=" + msg + " /LinkURL=@ /Color=#FFFA9D /Delay=3";
    //
    objCommon.RunExe(wizShellFileName, params, false);
}

function download() {
    //
    var section = "GoogleReader";
    //
    var starred = getIni(section, "StarredOnly", "") == "1";
    var contentOnly = getIni(section, "ContentOnly", "1") == "1";
    var useContentInFeed = getIni(section, "UseContentInFeed", "") == "1";
    var count = parseInt(getIni(section, "Count", "100"));
    //
    
    var objXml = downloadCore(starred, count);
    if (!objXml) {
        var msg = loadString("strGoogleReaderFailed");
        jsAlert(msg);
        return;
    }
    //
    var myDate = new Date();
    var year = myDate.getFullYear();
    var month = myDate.getMonth() + 1;
    var day = myDate.getDate();
    //
    var baseName = loadString("strBlogs");
    if (baseName == null || baseName == "") {
        baseName = "Blogs";
    }
    //
    var baseLocation = "/" + baseName + "/";
    //
    var location = baseLocation + "Google Eeader" + "/" + year + "/" + formatInt(month) + "/";
    var databasePath = objDatabase.DatabasePath;
    //
    var flags = 0;
    if (contentOnly) {
        flags |= 0x08;
    }
    //
    var root = objXml.documentElement;
    //
    var children = root.childNodes;
    //
    var progress = objCommon.CreateWizObject("WizKMControls.WizProgressWindow");
    progress.Title = "Google Reader";
    progress.Show();
    //
    progress.Max = children.length;
    //
    var needDownload = false;
    //
    var downloaded = false;
    //
    for (var i = 0; i < children.length; i++) {
        var node = children.item(i);
        //
        if (node.tagName != "entry")
            continue;
        //
        var nodeURL = node.selectSingleNode("link");
        if (!nodeURL)
            continue;
        //
        var urlAttr = nodeURL.attributes.getNamedItem("href");
        if (!urlAttr)
            continue;
        //
        var url = urlAttr.value;
        if (!url || url == "")
            continue;

        var title = "";

        var nodeTitle = node.selectSingleNode("title");
        if (nodeTitle) {
            title = nodeTitle.text;
        }
        if (!title)
            title = "";
        //
        //
        try {
            var documents = objDatabase.DocumentsFromURL(url);
            if (documents != null && documents.Count > 0)
                continue;
        }
        catch (e) {
        }
        //

        if (useContentInFeed == "1") {
            var replaceReturn = false;
            var nodeContent = node.selectSingleNode("content");
            if (!nodeContent) {
                nodeContent = node.selectSingleNode("summary");
                replaceReturn = true;
            }
            //
            if (nodeContent) {
                //
                progress.Text = title;
                //
                //
                var text = nodeContent.text;
                //
                text = text.replace(/\xA0/g, "&#160;");
                if (replaceReturn) {
                    text = text.replace(/\r\n/g, "\n");
                    text = text.replace(/\r/g, "\n");
                    text = text.replace(/\n/g, "<br />\n");
                }
                //
                text = "<!--WizHtmlContentBegin-->" + text + "<!--WizHtmlContentBegin-->";
                //
                var folder = objDatabase.GetFolderByLocation(location, true);
                var doc = folder.CreateDocument2(title, url);
                doc.UpdateDocument4(text, url, flags);
                //
                doc.Type = "webclip";
                //
                progress.Pos = i + 1;
                //
                downloaded = true;
//lst新增加添加标签功能 
                var tagNodes=node.getElementsByTagName("category");
                var tagText="";
                for (var j = 0; j < tagNodes.length; j++) {
                  if (tagTex=tagNodes [j].attributes.getNamedItem("term").value.match("/label/")) {
                       var tagTex=tagNodes [j].attributes.getNamedItem("label").value;
                        tagText =tagText+ ";" + tagTex;
                      }
                  }
                if (tagText != "") { 
                    doc.TagsText =tagText; }
                //
                continue;
            }
        }
        //
        objDownloader.AddJob(databasePath, location, url, title, flags, true, true);
        //
        needDownload = true;
    }
    //
    progress.Hide();
    //
    if (needDownload) {
        objDownloader.Title = "Google Reader";
        objDownloader.ShowWindow(true);
    }
    else {
        if (!downloaded) {
            showBubbleMessage("Google Reader", loadString("strNoNewItems"));
        }
    }
}

download();