/*
 * Copyright (c) 2011 by RibbonSoft, GmbH. All rights reserved.
 * 
 * This file is part of the QCAD project.
 *
 * Licensees holding valid QCAD Professional Edition licenses 
 * may use this file in accordance with the QCAD License
 * Agreement provided with the Software.
 *
 * This file is provided AS IS with NO WARRANTY OF ANY KIND, 
 * INCLUDING THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS 
 * FOR A PARTICULAR PURPOSE.
 * 
 * See http://www.ribbonsoft.com for further details.
 */

include("scripts/Widgets/LibraryBrowser/LibraryBrowser.js");
include("../../File/File.js");
include("../Block.js");
include("../BlockDialog.js");

function CreateLibraryItem(guiAction) {
    Block.call(this, guiAction);

    this.referencePoint = undefined;
}

CreateLibraryItem.prototype = new Block();

CreateLibraryItem.State = {
    SettingPosition : 0
};

CreateLibraryItem.prototype.beginEvent = function() {
    Block.prototype.beginEvent.call(this);

    this.setState(CreateLibraryItem.State.SettingPosition);
};

CreateLibraryItem.prototype.setState = function(state) {
    Block.prototype.setState.call(this, state);

    this.setCrosshairCursor();
    this.getDocumentInterface().setClickMode(RAction.PickCoordinate);

    this.setLeftMouseTip(qsTr("Reference Point"));
    this.setRightMouseTip(EAction.trCancel);

    EAction.showSnapTools();
};

CreateLibraryItem.prototype.coordinateEvent = function(event) {
    var pos = event.getModelPosition();
    this.getDocumentInterface().setRelativeZero(pos);
    this.referencePoint = pos;

    var di = this.getDocumentInterface();
    var document = this.getDocument();

    var itemStorage = new RMemoryStorage();
    var itemSpatialIndex = new RSpatialIndexNavel();
    var itemDocument = new RDocument(itemStorage, itemSpatialIndex);
    var itemDocumentInterface = new RDocumentInterface(itemDocument);

    var op = new RCopyOperation(pos.getNegated(), document);
    itemDocumentInterface.applyOperation(op);

    var res = File.getSaveFileName(
        EAction.getMainWindow(),
        qsTr("Save library item as..."),
        RSettings.getLaunchPath() + "/libraries",
        RFileExporterRegistry.getFilterStrings());

    if (!isNull(res)) {
        itemDocumentInterface.exportFile(res[0], res[1]);
        LibraryBrowser.showDirectory(new QFileInfo(res[0]).absolutePath());
    }

    itemDocumentInterface.destroy();
    this.terminate();
};
