/*
 * Copyright (c) 2018 by Filestack.
 * Some rights reserved.
 *
 * 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.
 */
import { removeEmpty } from '../utils';
import { requestWithSource, request } from '../api/request';
import { FilestackError } from './../../filestack_error';
/**
 * @private
 */
export var PICKER_KEY = '__fs_picker_token';
/**
 * @private
 */
var CloudClient = /** @class */ (function () {
    function CloudClient(session, options) {
        this.cache = false;
        this.session = session;
        this.cloudApiUrl = session.urls.cloudApiUrl;
        if (options && options.sessionCache) {
            this.cache = options.sessionCache;
        }
    }
    Object.defineProperty(CloudClient.prototype, "token", {
        get: function () {
            if (this.cache) {
                var token = localStorage.getItem(PICKER_KEY);
                if (token)
                    return token;
            }
            return this._token;
        },
        set: function (key) {
            if (this.cache) {
                localStorage.setItem(PICKER_KEY, key);
            }
            this._token = key;
        },
        enumerable: true,
        configurable: true
    });
    CloudClient.prototype.prefetch = function () {
        var params = {
            apikey: this.session.apikey,
        };
        return requestWithSource()
            .get(this.cloudApiUrl + "/prefetch", { params: params })
            .then(function (res) { return res.data; });
    };
    CloudClient.prototype.list = function (clouds, token) {
        var _this = this;
        var payload = {
            apikey: this.session.apikey,
            clouds: clouds,
            flow: 'web',
            token: this.token,
        };
        if (this.session.policy && this.session.signature) {
            payload.policy = this.session.policy;
            payload.signature = this.session.signature;
        }
        var options = {};
        if (token) {
            var CancelToken = request.CancelToken;
            var source = CancelToken.source();
            token.cancel = source.cancel;
            options.cancelToken = source.token;
        }
        return requestWithSource()
            .post(this.cloudApiUrl + "/folder/list", payload, options)
            .then(function (res) {
            if (res.data && res.data.token) {
                _this.token = res.data.token;
            }
            return res.data;
        });
    };
    CloudClient.prototype.store = function (name, path, options, customSource, token) {
        var _this = this;
        var _a;
        if (options === void 0) { options = {}; }
        if (customSource === void 0) { customSource = {}; }
        // Default to S3
        if (options.location === undefined)
            options.location = 's3';
        var payload = {
            apikey: this.session.apikey,
            token: this.token,
            flow: 'web',
            clouds: (_a = {},
                _a[name] = {
                    path: path,
                    store: removeEmpty(options),
                },
                _a),
        };
        if (name === 'customsource' && customSource.customSourcePath) {
            payload.clouds.customsource.customSourcePath = customSource.customSourcePath;
        }
        if (name === 'customsource' && customSource.customSourceContainer) {
            payload.clouds.customsource.customSourceContainer = customSource.customSourceContainer;
        }
        if (this.session.policy && this.session.signature) {
            payload.policy = this.session.policy;
            payload.signature = this.session.signature;
        }
        var requestOptions = {};
        if (token) {
            var CancelToken = request.CancelToken;
            var source = CancelToken.source();
            token.cancel = source.cancel;
            requestOptions.cancelToken = source.token;
        }
        return requestWithSource()
            .post(this.cloudApiUrl + "/store/", payload, requestOptions)
            .then(function (res) {
            if (res.data && res.data.token) {
                _this.token = res.data.token;
            }
            if (res.data && res.data[name]) {
                return res.data[name];
            }
            return res.data;
        });
    };
    CloudClient.prototype.logout = function (name) {
        var _a;
        var payload = {
            apikey: this.session.apikey,
            flow: 'web',
            token: this.token,
        };
        if (name) {
            payload.clouds = (_a = {}, _a[name] = {}, _a);
        }
        else if (this.cache) {
            // No name means logout of ALL clouds. Clear local session.
            localStorage.removeItem(PICKER_KEY);
        }
        return requestWithSource()
            .post(this.cloudApiUrl + "/auth/logout/", payload)
            .then(function (res) {
            if (res.data && res.data[name]) {
                return res.data[name];
            }
            return res.data;
        });
    };
    CloudClient.prototype.metadata = function (url) {
        var payload = {
            apikey: this.session.apikey,
            url: url,
        };
        if (this.session.policy && this.session.signature) {
            payload.policy = this.session.policy;
            payload.signature = this.session.signature;
        }
        return requestWithSource()
            .post(this.cloudApiUrl + "/metadata/", payload)
            .then(function (res) { return res.data; });
    };
    // OpenTok API Endpoints
    CloudClient.prototype.tokInit = function (type) {
        if (type !== 'video' && type !== 'audio') {
            throw new FilestackError('Type must be one of video or audio.');
        }
        return requestWithSource()
            .post(this.cloudApiUrl + "/recording/" + type + "/init")
            .then(function (res) {
            return {
                body: res.data,
            };
        });
    };
    CloudClient.prototype.tokStart = function (type, key, sessionId) {
        if (type !== 'video' && type !== 'audio') {
            throw new FilestackError('Type must be one of video or audio.');
        }
        var payload = {
            apikey: key,
            session_id: sessionId,
        };
        return requestWithSource()
            .post(this.cloudApiUrl + "/recording/" + type + "/start", payload)
            .then(function (res) {
            return {
                body: res.data,
            };
        });
    };
    CloudClient.prototype.tokStop = function (type, key, sessionId, archiveId) {
        if (type !== 'video' && type !== 'audio') {
            throw new FilestackError('Type must be one of video or audio.');
        }
        var payload = {
            apikey: key,
            session_id: sessionId,
            archive_id: archiveId,
        };
        return requestWithSource()
            .post(this.cloudApiUrl + "/recording/" + type + "/stop", payload)
            .then(function (res) {
            return {
                body: res.data,
            };
        });
    };
    return CloudClient;
}());
export { CloudClient };
