/**
 * 媒体相关接口
 */
import { callNative, emptyFn, typeCheck, getUid, callNativeSync } from './util';

const PreviewImageComponents = {};

export default {
    PreviewImageComponents,
    /**
     * 在新页面中全屏预览图片。
     *
     * @param {Object} options
     * @param {Array} options.urls 成功回调
     * @param {String} options.current 当前显示图片的链接，不填则默认为 urls 的第一张
     * @param {String} options.desc 底部描述
     * @param {Object} options.bottomConfig key表示对应第几个区块，一共4个，从左到右对应1 2 3 4，iconPath为图标url，desc为图标后面跟着的描述
     * @param {Object} options.rightConfig 最后一张图片再向左滑动时出现的展示配置
     * @param {Function} options.onBottomClick 底部按钮点击后的回调
     * @param {Function} options.onClose 关闭组件后的回调
     * @param {Function} options.success 成功回调
     * @param {Function} options.fail 失败回调
     */
    previewImage(options = {}) {
        let currentIndex = 0;
        let componentId = 0;
        const callbackId = getUid();
        const successFn = typeof options.success === 'function' ? options.success : emptyFn;
        const failFn = typeof options.fail === 'function' ? options.fail : emptyFn;
        const completeFn = typeof options.complete === 'function' ? options.complete : emptyFn;
        const closeFn = typeof options.onClose === 'function' ? options.onClose : emptyFn;
        const bottomFn = typeof options.onBottomClick === 'function' ? options.onBottomClick : emptyFn;
        const rightFn = options.rightConfig ? (typeof options.rightConfig.callback === 'function' ? options.rightConfig.callback : emptyFn) : emptyFn;
        const systemInfo = callNativeSync('getSystemInfoSync').data;

        if (systemInfo.platform === 'android' && systemInfo.SDKVersion === '2.1.0') {
            failFn({ errMsg: 'not support SDKVersion 2.1.0 in Android' });
            return;
        }

        if (!Array.isArray(options.urls)) {
            failFn({ errMsg: 'previewImage:fail parameter error: parameter.urls should be Array<String>' });
            return;
        }

        if (options.urls.length === 0) {
            failFn({ errMsg: 'previewImage:fail at least 1 item needed' });
            return;
        }

        for (let i = 0; i < options.urls.length; i++) {
            const element = options.urls[i];
            const result = typeCheck(element, 'String');
            if (result) {
                failFn({ errMsg: `previewImage:fail parameter error: urls[${i}] should be String instead of ${result};` });
                return;
            }
        }

        if (options.current) {
            currentIndex = Math.max(0, options.urls.indexOf(options.current));
        }

        const optionsToNative = Object.assign({}, options, { current: currentIndex });

        const callbackFn = (result) => {
            if (result.code === 0) {
                componentId = result.data.id;
                PreviewImageComponents[componentId] = {
                    bottomFn,
                    rightFn,
                    closeFn
                };

                successFn(Object.assign({ errMsg: 'previewImage:ok' }, Object.prototype.toString.call(result.data) === '[object Object]' ? result.data : { data: result.data }));
                completeFn(Object.assign({ errMsg: 'previewImage:ok' }, Object.prototype.toString.call(result.data) === '[object Object]' ? result.data : { data: result.data }));
            } else {
                failFn({ errMsg: result.msg });
                completeFn({ errMsg: result.msg });
            }
        };

        Service.callbacks[callbackId] = callbackFn;
        Service.callNative('previewImage', JSON.stringify(optionsToNative), callbackId);
    },
    /**
     * 保存图片到系统相册。
     *
     * @param {Object} options
     * @param {Array} options.filePath 图片文件路径，可以是临时文件路径或永久文件路径
     * @param {Function} options.success 成功回调
     * @param {Function} options.fail 失败回调
     */
    saveImageToPhotosAlbum(options = {}) {
        callNative('saveImageToPhotosAlbum', options, { filePath: 'String' });
    },
    chooseImage({
        count = 9,
        sizeType = ['original', 'compressed'],
        sourceType = ['album', 'camera'],
        success = emptyFn,
        fail = emptyFn,
        complete = emptyFn,
    } = {}) {
        const successFn = function (res) {
            if (!res.tempFilePaths) {
                res.tempFilePaths = res.tempFiles.map(item => item.path);
            }
            success(res);
        };
        const options = {
            count,
            sizeType,
            sourceType,
            success: successFn,
            fail,
            complete,
        };
        callNative('chooseImage', options, { count: 'Number' }, 'chooseImage', {
            resultFn(result){
                let errorInfo = ''
                if (Number(result.code) === 101 || Number(result.code) === 1300) {
                    errorInfo = `cancel`;
                } else if (Number(result.code) === 900) {
                    errorInfo = `failed to write the choosed image to temporary file`;
                } else {
                    errorInfo = 'failed to write the choosed image to temporary file';
                }
                return errorInfo;
            }
        });
    },
};
