/****************************************************************************
* SKCD  > skPrintManager                                                    *
*---------------------------------------------------------------------------*
* skPrintManager gives three different ways to print a document :           *
* First, the printing manager can use the global settings (defined          *
* previously under other application). Then, it gives the possibility to    *
* print using settings previously defined one by one by skPrintManager.     *
* Finally, new settings can be used.                                        *
*---------------------------------------------------------------------------*
* (c) IDM. 2003                                                             *
* Project  : sk                                                             *
* Language : javascript                                                     *
* Created  : MikaelLebrun, 25/02/2003                                       *
****************************************************************************/

const PRINT_SETTINGS_STRING = new Array("toFileName",
                                        "title",
                                        "docURL",
                                        "footerStrCenter",
                                        "printerName",
                                        "headerStrCenter",
                                        "headerStrRight",
                                        "headerStrLeft",
                                        "paperName",
                                        "footerStrRight",
                                        "printCommand",
                                        "footerStrLeft"
                                        );

const PRINT_SETTINGS_DOUBLE = new Array("marginTop",
                                        "marginLeft",
                                        "paperWidth",
                                        "marginBottom",
                                        "paperHeight",
                                        "marginRight",
                                        "scaling"
                                        );

const PRINT_SETTINGS_INTEGER = new Array("paperData",
                                         "howToEnableFrameUI",
                                         "orientation",
                                         "paperSizeType",
                                         "printRange",
                                         "printPageDelay",
                                         "printFrameTypeUsage",
                                         "printFrameType",
                                         "paperSize",
                                         "endPageRange",
                                         "startPageRange",
                                         "paperSizeUnit",
                                         "numCopies"
                                        );

const PRINT_SETTINGS_BOOLEAN = new Array("showPrintProgress",
                                         "printBGImages",
                                         "printBGColors",
                                         "printReversed",
                                         "printToFile",
                                         "printSilent",
                                         "printInColor",
                                         "isCancelled",
                                         "shrinkToFit",
                                         "isPrintPreview"
                                        );

const PRINT_PREF_BRANCH = "skprint.";

function skPrintManager() { } //skPrintManager object

skPrintManager.prototype = {

    QueryInterface:function(iid) {
        if (!iid.equals(Components.interfaces.skIPrintManager)
            &&!iid.equals(Components.interfaces.nsISupports)) {
            throw Components.results.NS_ERROR_NO_INTERFACE;
        }
        return this;
    },
     
    /*############### WORKS THE SECOND TIME MOZILLA IS LAUNCHED !!!! #####################*/
    /*********************************************************************************************
    FUNCTION : AddPrintSettingsToPrefs()
    This function save the setting given in parameter into the preferences file (which filename is
    'prefs.js').
    ****INPUT: 1/ a string [psSettingName - the setting name]
               2/ a string [psSettingValue - the setting value; always a string, even for settings which 
                            type is boolean, integer or double settings]
    ****OUPUT: NOTHING
    ********************************************************************************************/
    AddPrintSettingsToPrefs:function(psSettingName, psSettingValue) {
        try {
            //this.window = pxiWindow;
            var xiPref = Components.classes["@mozilla.org/preferences;1"].getService(Components.interfaces.nsIPref);
            var xiPrefBranch = xiPref.getBranch(PRINT_PREF_BRANCH);

            //Set boolean settings
            if (this.searchInArray(PRINT_SETTINGS_BOOLEAN, psSettingName)) {
                if (psSettingValue.toLowerCase() == "true")
                    xiPrefBranch.setBoolPref(psSettingName, true);
                else
                    xiPrefBranch.setBoolPref(psSettingName, false);
            }
            //Set character settings
            else if (this.searchInArray(PRINT_SETTINGS_STRING, psSettingName))
                xiPrefBranch.setCharPref(psSettingName, psSettingValue);
            //Set double settings
            else if (this.searchInArray(PRINT_SETTINGS_DOUBLE, psSettingName))
                xiPrefBranch.setCharPref(psSettingName, psSettingValue);
            //Set integer settings
            else if (this.searchInArray(PRINT_SETTINGS_INTEGER, psSettingName))
                xiPrefBranch.setIntPref(psSettingName, psSettingValue);
            //xiPref.savePrefFile(null);
        } catch(err) {
            dump( err);
        }
    },

    /*********************************************************************************************
    FUNCTION : searchInArray()
    This function search if a value is contained in a given array.
    ****INPUT: 1/ an array [paArray - the array in which we will search the given value]
               2/ a string [psSearchValue - the value searched in the array]
    ****OUPUT: a boolean [true if the value is found in the array, otherwise false.]
    ********************************************************************************************/
    searchInArray:function(paArray, psSearchValue) {
        for (var i=0; i<paArray.length; i++) {
            if (paArray[i] == psSearchValue)
                return true;
        }
        return false;
    },
    
    /*############### WORKS THE SECOND TIME MOZILLA IS LAUNCHED !!!! #####################*/
    /*********************************************************************************************
    FUNCTION : Print()
    This function print any document using one of the three settings available
    ****INPUT: 1/ a window object [pxiWindow - the window we want to print]
               2/ an integer [piSettingsMode - a defined settings mode :
                                               1- use the global settings
                                               2- use skPrintManager settings (see AddPrintSettingsToPrefs)
                                               3- use new (empty) settings]
    ****OUPUT: NOTHING
    ********************************************************************************************/
    Print:function(pxiWindow, piSettingsMode) {
        try {
            //this.window = pxiWindow;
            if(pxiWindow) {
                var xiInterfaceRequestor = pxiWindow.QueryInterface(Components.interfaces.nsIInterfaceRequestor);
                var xiWebBrowserPrint = xiInterfaceRequestor.getInterface(Components.interfaces.nsIWebBrowserPrint);
                if (xiWebBrowserPrint) {
                    var xiPrintSettings = this.getPrintSettings(piSettingsMode);
                    xiWebBrowserPrint.print(xiPrintSettings, null);
                }
            }
         } catch (err) {
            // Pressing cancel is expressed as an NS_ERROR_ABORT return value,
            // causing an exception to be thrown which we catch here.
            dump(err);
         }
    },

    /*********************************************************************************************
    FUNCTION : getPrintSettings()
    This function prepare all settings that will be used for the printing
    ****INPUT: 1/ an integer [piSettingsMode - a defined settings mode :
                                               1- return the global settings
                                               2- return skPrintManager settings (see AddPrintSettingsToPrefs)
                                               3- return new (empty) settings]
    ****OUPUT: an XPCOM nsIPrintSettings interface
    ********************************************************************************************/
    getPrintSettings:function(piSettingsMode) {
        var xiPrintSettings;
        try {
            var xiPrintSettingsService = Components.classes["@mozilla.org/gfx/printsettings-service;1"]
                                       .getService(Components.interfaces.nsIPrintSettingsService);

            if (piSettingsMode == 1) {
                // 1- return the global settings
                xiPrintSettings = xiPrintSettingsService.globalPrintSettings;
                if (xiPrintSettings.printerName == "")
                    xiPrintSettings.printerName = xiPrintSettingsService.defaultPrinterName;
                //Get any defaults from the printer 
                xiPrintSettingsService.initPrintSettingsFromPrinter(xiPrintSettings.printerName, xiPrintSettings);
                //Augment them with any values from last time
                xiPrintSettingsService.initPrintSettingsFromPrefs(xiPrintSettings, true, xiPrintSettings.kInitSaveAll);
            } else if(piSettingsMode == 2) {
                // 2- return skPrintManager settings (see AddPrintSettingsToPrefs)
                xiPrintSettings = xiPrintSettingsService.globalPrintSettings;
                if (xiPrintSettings.printerName == "")
                    xiPrintSettings.printerName = xiPrintSettingsService.defaultPrinterName;
                //Get any defaults from the printer 
                xiPrintSettingsService.initPrintSettingsFromPrinter(xiPrintSettings.printerName, xiPrintSettings);
                //Augment them with any values from last time
                xiPrintSettingsService.initPrintSettingsFromPrefs(xiPrintSettings, true, xiPrintSettings.kInitSaveAll);
                var xiPref = Components.classes["@mozilla.org/preferences;1"].getService(Components.interfaces.nsIPref);
                var xiPrefBranch = xiPref.getBranch(PRINT_PREF_BRANCH);
                var prefCount = {value:0};
                var aPrefArray = xiPrefBranch.getChildList("", prefCount);
                var sPrefBranchType;
                
                for (var i=0; i<aPrefArray.length; i++) {
                    sPrefBranchType = xiPrefBranch.getPrefType(aPrefArray[i]);
                    if (sPrefBranchType == xiPrefBranch.PREF_STRING) {
                        switch (aPrefArray[i]) {
                            case "docURL":
                                xiPrintSettings.docURL = xiPrefBranch.getCharPref(aPrefArray[i]);
                                break;
                            case "footerStrCenter":
                                xiPrintSettings.footerStrCenter = xiPrefBranch.getCharPref(aPrefArray[i]);
                                break;
                            case "footerStrLeft":
                                xiPrintSettings.footerStrLeft = xiPrefBranch.getCharPref(aPrefArray[i]);
                                break;
                            case "footerStrRight":
                                xiPrintSettings.footerStrRight = xiPrefBranch.getCharPref(aPrefArray[i]);
                                break;
                            case "headerStrCenter":
                                xiPrintSettings.headerStrCenter = xiPrefBranch.getCharPref(aPrefArray[i]);
                                break;
                            case "headerStrLeft":
                                xiPrintSettings.headerStrLeft = xiPrefBranch.getCharPref(aPrefArray[i]);
                                break;
                            case "headerStrRight":
                                xiPrintSettings.headerStrRight = xiPrefBranch.getCharPref(aPrefArray[i]);
                                break;
                            case "paperName":
                                xiPrintSettings.paperName = xiPrefBranch.getCharPref(aPrefArray[i]);
                                break;
                            case "printCommand":
                                xiPrintSettings.printCommand = xiPrefBranch.getCharPref(aPrefArray[i]);
                                break;
                            case "printerName":
                                xiPrintSettings.printerName = xiPrefBranch.getCharPref(aPrefArray[i]);
                                break;
                            case "title":
                                xiPrintSettings.title = xiPrefBranch.getCharPref(aPrefArray[i]);
                                break;
                            case "toFileName":
                                xiPrintSettings.toFileName = xiPrefBranch.getCharPref(aPrefArray[i]);
                                break;
                            case "marginBottom":
                                xiPrintSettings.marginBottom = xiPrefBranch.getCharPref(aPrefArray[i]);
                                break;
                            case "marginLeft":
                                xiPrintSettings.marginLeft = xiPrefBranch.getCharPref(aPrefArray[i]);
                                break;
                            case "marginRight":
                                xiPrintSettings.marginRight = xiPrefBranch.getCharPref(aPrefArray[i]);
                                break;
                            case "marginTop":
                                xiPrintSettings.marginTop = xiPrefBranch.getCharPref(aPrefArray[i]);
                                break;
                            case "paperHeight":
                                xiPrintSettings.paperHeight = xiPrefBranch.getCharPref(aPrefArray[i]);
                                break;
                            case "paperWidth":
                                xiPrintSettings.paperWidth = xiPrefBranch.getCharPref(aPrefArray[i]);
                                break;
                            case "scaling":
                                xiPrintSettings.scaling = xiPrefBranch.getCharPref(aPrefArray[i]);
                                break;
                            default :
                                break;
                        }
                    } else if (sPrefBranchType == xiPrefBranch.PREF_INT) {
                         switch (aPrefArray[i]) {
                            case "paperData":
                                xiPrintSettings.paperData = xiPrefBranch.getIntPref(aPrefArray[i]);
                                break;
                            case "howToEnableFrameUI":
                                xiPrintSettings.howToEnableFrameUI = xiPrefBranch.getIntPref(aPrefArray[i]);
                                break;
                            case "orientation":
                                xiPrintSettings.orientation = xiPrefBranch.getIntPref(aPrefArray[i]);
                                break;
                            case "paperSizeType":
                                xiPrintSettings.paperSizeType = xiPrefBranch.getIntPref(aPrefArray[i]);
                                break;
                            case "printRange":
                                xiPrintSettings.printRange = xiPrefBranch.getIntPref(aPrefArray[i]);
                                break;
                            case "printPageDelay":
                                xiPrintSettings.printPageDelay = xiPrefBranch.getIntPref(aPrefArray[i]);
                                break;
                            case "printFrameTypeUsage":
                                xiPrintSettings.printFrameTypeUsage = xiPrefBranch.getIntPref(aPrefArray[i]);
                                break;
                            case "printFrameType":
                                xiPrintSettings.printFrameType = xiPrefBranch.getIntPref(aPrefArray[i]);
                                break;
                            case "paperSize":
                                xiPrintSettings.paperSize = xiPrefBranch.getIntPref(aPrefArray[i]);
                                break;
                            case "endPageRange":
                                xiPrintSettings.endPageRange = xiPrefBranch.getIntPref(aPrefArray[i]);
                                break;
                            case "startPageRange":
                                xiPrintSettings.startPageRange = xiPrefBranch.getIntPref(aPrefArray[i]);
                                break;
                            case "paperSizeUnit":
                                xiPrintSettings.paperSizeUnit = xiPrefBranch.getIntPref(aPrefArray[i]);
                                break;
                            case "numCopies":
                                xiPrintSettings.numCopies = xiPrefBranch.getIntPref(aPrefArray[i]);
                                break;
                            default :
                                break;
                         }
                    } else if (sPrefBranchType == xiPrefBranch.PREF_BOOL) {
                         switch (aPrefArray[i]) {
                            case "isCancelled":
                                xiPrintSettings.isCancelled = xiPrefBranch.getBoolPref(aPrefArray[i]);
                                break;
                            case "isPrintPreview":
                                xiPrintSettings.isPrintPreview = xiPrefBranch.getBoolPref(aPrefArray[i]);
                                break;
                            case "printBGColors":
                                xiPrintSettings.printBGColors = xiPrefBranch.getBoolPref(aPrefArray[i]);
                                break;
                            case "printBGImages":
                                xiPrintSettings.printBGImages = xiPrefBranch.getBoolPref(aPrefArray[i]);
                                break;
                            case "printInColor":
                                xiPrintSettings.printInColor = xiPrefBranch.getBoolPref(aPrefArray[i]);
                                break;
                            case "printReversed":
                                xiPrintSettings.printReversed = xiPrefBranch.getBoolPref(aPrefArray[i]);
                                break;
                            case "printSilent":
                                xiPrintSettings.printSilent = xiPrefBranch.getBoolPref(aPrefArray[i]);
                                break;
                            case "printToFile":
                                xiPrintSettings.printToFile = xiPrefBranch.getBoolPref(aPrefArray[i]);
                                break;
                            case "showPrintProgress":
                                xiPrintSettings.showPrintProgress = xiPrefBranch.getBoolPref(aPrefArray[i]);
                                break;
                            case "shrinkToFit":
                                xiPrintSettings.shrinkToFit = xiPrefBranch.getBoolPref(aPrefArray[i]);
                                break;
                            default :
                                break; catalog 
                         }
                    }
                }
            } else if (piSettingsMode == 3) {
                //3- return new (empty) settings]
                xiPrintSettings = xiPrintSettingsService.newPrintSettings;
            }
        } catch (err) {
             dump(err+"\n"); //########
        }
        return xiPrintSettings;
    }

    /*
    dump:function(pxiWindow, psTitle, psText) {
        var xiDumpService = Components.classes["@mozilla.org/embedcomp/dump-service;1"].createInstance().QueryInterface(Components.interfaces.nsIDumpService);
        xiDumpService.alert(pxiWindow, psTitle, psText);
    }
    */
}

var skPrintManagerModule = {

    registerSelf: function (compMgr, fileSpec, location, type) {
        compMgr = compMgr.QueryInterface(Components.interfaces.nsIComponentRegistrar);
        compMgr.registerFactoryLocation(this.myCID,
                                        "Sk PrintManager Component",
                                        this.myProgID, 
                                        fileSpec,
                                        location,
                                        type);
    },

    getClassObject: function (compMgr, cid, iid) {
        if (!cid.equals(this.myCID))
            throw Components.results.NS_ERROR_NO_INTERFACE;
        if (!iid.equals(Components.interfaces.nsIFactory))
            throw Components.results.NS_ERROR_NOT_IMPLEMENTED;
        return this.myFactory;
    },

    myCID: Components.ID("b5b8bb12-650c-4197-bf24-48d9d75f0019"),

    myProgID: "@idm.fr/sk_print_manager;1",

    myFactory: {
        createInstance: function (outer, iid) {
            if (outer != null)
                throw Components.results.NS_ERROR_NO_AGGREGATION;
            return (new skPrintManager()).QueryInterface(iid);
        }
    },

    canUnload: function(compMgr) {
        return true;
    }
};

function NSGetModule(compMgr, fileSpec) { return skPrintManagerModule; }
