/* 
 Copyright 2005-2010 Xmarks Inc.
 
 foxmarks-progress.js: handles the UI and top-level logic for
 merge, sync, upload, and download operations.
  
 */

var gCancelled;
var gQuick;
var gSyncTypes = ["bookmarks", "history", "passwords", "tabs"];

var newObserver = {
    _document: null,
    _window: null,
    _component: null,
    _phase: null,

    observe: function(subject, topic, data) {
        var result = eval(data);
        if (result.component) {
            this._component = result.component;
        }
        if (result.phase) {
            this._phase = result.phase;
        }
        // Xmarks.LogWrite("Progress: " + data);
        if (this._document) {
            if(result.status == 1){
                // Status update
                if (this._component) {
                    var label = this._document.getElementById(this._component);
                    if (label) {
                        label.setAttribute("value",  
                            Xmarks.Bundle().GetStringFromName(
                                this._phase == "end" ?  "progress.sync.done" :
                                "progress.sync.working"));
                    }
                    var image = this._document.getElementById(this._component + 
                            "-check");
                    if(image){
                        image.setAttribute("src", this._phase == "end" ?
                            "chrome://foxmarks/skin/images/progress-good.png":
                            "chrome://foxmarks/skin/images/wheel.gif"
                        );
                    }
                }
            } else { // complete?
                this._window.arguments[1].status = result.status;
                this._window.arguments[1].msg = result.msg;
                this._window.arguments[1].result = result;
                if (gQuick) {
                    setTimeout(this._window.close, 1000);
                } else {
                    gCancelled = true;
                    setTimeout(this._window.close, 100);
                }
            }
        }        
        try {
            this._window.sizeToContent();
        } catch(e) {}
    },

    adjustDialogButtons: function(status) {
        var d = this._document.documentElement;
        var help = d.getButton("help");
        help.hidden = (status >= 0 && status <= 2);
        var cancel = d.getButton("cancel");
        cancel.hidden = (status != 1);
        try {
            this._window.sizeToContent();
        } catch(e) {}
    }
};

var Cc = Components.classes;
var Ci = Components.interfaces;
var Cu = Components.utils;

function onProgressLoad() {
    Cu.import("resource://xmarks/service.jsm", Xmarks);

    gCancelled = false;
    gQuick = false;

    // Initialize enabled/disabled labels
    var len = gSyncTypes.length;
    var x;
    for(x = 0; x < len; x++){
        var type = gSyncTypes[x];
        var label = document.getElementById(type);
        label.setAttribute("value", Xmarks.Bundle().GetStringFromName(
                Xmarks.gSettings.isSyncEnabled(type) ?
                "progress.sync.enabled" : "progress.sync.disabled"));
    }

    var os = Cc["@mozilla.org/observer-service;1"].
        getService(Ci.nsIObserverService);
    newObserver._document = document;
    newObserver._window = window;
    os.addObserver(newObserver, "foxmarks-service", false);
    
    var okay = false;

    switch (window.arguments[0]) {
        case "upload":
            gQuick = false;
            okay = Xmarks.fms.upload();
            break;
        
        case "restore":
            gQuick = false;
            okay = Xmarks.fms.restore(window.arguments[2]);
            break;
            
        case "download":
            gQuick = false;
            okay = Xmarks.fms.download();
            break;
        
        case "deletepasswords":
            gQuick = false;
            document.getElementById("lineitems").setAttribute("hidden", "true");
            okay = Xmarks.fms.purgepasswords();
            break;
        case "synch":
            gQuick = false;
            okay = Xmarks.fms.synchronize();
            break;

        case "syncDirty":
            gQuick = false;
            okay = Xmarks.fms.synchronize(true, true);
            break;

        case "status":
            gQuick = true;
            okay = Xmarks.fms.status();
            break;
            
        case "initialSync":
            var ca = window.arguments[2];
            gQuick = true;
            okay = Xmarks.fms.synchronizeInitial(ca.remoteIsMaster, 
                ca.merge);
            break;
    }

    if (!okay) {
        // Service is busy. Disconnect the observer and simulate a
        // "busy" status message.
        onProgressUnload();
        newObserver.observe(null, null,
            { msg: Xmarks.Bundle().GetStringFromName("msg.busy"), status: 4 }.
            toSource());
    }
}

function onProgressUnload() {
    var os = Cc["@mozilla.org/observer-service;1"].
        getService(Ci.nsIObserverService);
    try {
        os.removeObserver(newObserver, "foxmarks-service");
    } catch (e) { }
}

function onProgressCancel() {
    Xmarks.fms.cancel();
  
    // the first time through, just let callbacks from the cancellation
    // requests above shut us down
    // if we somehow got stuck, allow a second press of the cancel
    // button to actually shut the dialog box down.
    
    if (gCancelled) {
        window.arguments[1].status = -1;
        window.arguments[1].msg = Xmarks.Bundle().GetStringFromName("msg.cancelled");
        return true;
    } else {
        gCancelled = true;
        return false;   // let the callbacks close us down
    }
}

function onProgressHelp() {
    var element = document.getElementById("status");
    if (element) {
        var errmsg = element.value.replace(/ /g, "_");
        window.arguments[1].helpurl =
            Xmarks.Bundle().formatStringFromName("url.error", [errmsg], 1);
        setTimeout(window.close, 100);
    }
    return false;
}
