import 'zone.js';
import {UserInfo} from 'user/UserInfo'
import {StringUtils} from '../utils/StringUtils'
import {format} from 'date-fns';
import * as fastify from 'fastify'

class Context {

    static USER_INFO_PROP_NAME: string = "RequestUser"
    static REQUEST_HEADER_PROP_NAME: string = "RequestHeader"
    static RESPONSE_HEADER_PROP_NAME: string = "FastifyResponse"
    static REQUEST_RAW_BODY_PROP_NAME: string = "RequestRawBody"

    /**
     * 获取当前上下文中的属性
     *
     * @param propName 属性名称
     */
    static get(propName: string): any {
        return Zone.current.get(propName);
    }

    /**
     * 获取当前用户信息
     */
    static getCurrentUser(): UserInfo {
        if (Zone && Zone.current) {
            return Zone.current.get(Context.USER_INFO_PROP_NAME) as UserInfo;
        } else {
            return null
        }
    }

    /**
     * 获取当前请求头信息
     */
    static getRequestHeaders(): any {
        if (Zone && Zone.current) {
            return Zone.current.get(Context.REQUEST_HEADER_PROP_NAME);
        } else {
            return {}
        }
    }

    /**
     * 获取当前请求原始信息
     */
    static getRequestRawBody(): any {
        if (Zone && Zone.current) {
            return Zone.current.get(Context.REQUEST_RAW_BODY_PROP_NAME);
        }
    }

    /**
     * 设置响应头信息
     */
    static setResponseHeader(name: string, value: string): boolean {
        const reply = Zone.current.get(Context.RESPONSE_HEADER_PROP_NAME);
        if (reply) {
            reply.header(name, value)
            return true
        }
        return false
    }

    /**
     * 获取当前用户信息
     */
    static currentUser(): UserInfo {
        return this.getCurrentUser();
    }

    /**
     * 获取环境变量
     * @param key 环境变量名称
     */
    static getEnv(key) {
        return process.env[key];
    }

    /**
     * 获取当前UTS定时任务执行日期 yyyyMMdd
     */
    static getUTSDate(): string {
        const date = this.getEnv('KT_UTS_DATE');
        if (StringUtils.isNotEmpty(date)) {
            return date
        } else {
            const now = new Date();
            return format(now, 'yyyyMMdd');
        }
    }


}

export {Context}