/**
 * distribution.js
 * Copyright (c)2000 - 2017 Samsung Electronics Co., Ltd. All rights reserved.
 *
 * Contact:
 * Sungmin Kim <sm.art.kim@samsung.com>
 * Jonghwan Park <iwin100.park@samsung.com>
 * Kitae Kim <kt920.kim@samsung.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Contributors:
 * - S-Core Co., Ltd
**/

'use strict';

var async = require('async');
var LockFile = require('lockfile');
var path = require('path');

var TizenDistribution = require('../org.tizen.ts.base.repository/distribution.js');

module.exports = TsDistribution;

function TsDistribution(name, distPath, options) {
    TizenDistribution.call(this, name, distPath, options);
}

TsDistribution.prototype = Object.create(TizenDistribution.prototype);
TsDistribution.constructor = TsDistribution;

TsDistribution.prototype.registerPackages = function (packagePathList, options, monitor, callback) {
    var self = this;
    async.series([
        function (cb) {
            acquireLock(self.path, cb);
        },
        function (cb) {
            TizenDistribution.prototype.registerPackages.call(self, packagePathList, options, monitor, cb);
        }
    ], function (err, newSnapshot) {
        releaseLock(self.path);
        callback(err, newSnapshot);
    });
};

function acquireLock(distPath, callback) {
    var lockFile = path.join(distPath, '.lock');
    LockFile.lock(lockFile, {wait: 1000 * 60 * 60}, function (err) {
        callback(err);
    });
}


function releaseLock(distPath) {
    var lockFile = path.join(distPath, '.lock');
    if (lockFile) {
        LockFile.unlockSync(lockFile);
    }
}
