/**
 *
 * @author: jiangfeng<jeff.jiang@yoho.cn>
 * @date: 16/8/22
 */

'use strict';

const http = require('http');
const logger = global.yoho.logger;
const env = process.env.NODE_ENV || 'development';

const hotfix = {
    v1(req, res) {
        let clientType = req.body.client_type || '';
        let version = req.body.app_version || '';

        let apiFile = `http://cdn.yoho.cn/app-hotfix2/${env}/yohobuy/`;

        if (clientType.toLowerCase() === 'ios' && version) {
            apiFile += `ios/${version}/api.json?_=` + (new Date()).getTime();
        } else if (clientType.toLowerCase() === 'android' && version) {
            apiFile += `android/${version}/api.json?_=` + (new Date()).getTime();
        } else {
            return res.json({
                code: 400,
                message: 'client_type or app_version error',
                data: {}
            });
        }

        http.get(apiFile, response => {
            res.setHeader('Content-Type', 'application/json');

            if (response.statusCode === 200) {
                response.pipe(res);
            } else {
                return res.json({
                    code: 400,
                    message: 'client_type or app_version error',
                    data: {}
                });
            }

        }).on('error', err => {
            logger.error('hot fix v1 error:', err);
            return res.json({
                code: 400,
                message: 'read api file fail',
                data: {}
            });
        });
    }
};

module.exports = hotfix;