import { DictionaryItem } from './dictionary-item.interface';

export class ModelHelper {

    public static manageDefaultDictionaryValue(object: any, property: string, defaultValue: any): DictionaryItem<any> {
        if (object === undefined || object === null) {
            return {};
        }
        if (object[property] === undefined || object[property] === null) {
            return {};
        }

        const currentDict = object[property];
        const dict: DictionaryItem<any> = [];
        for (const key of Object.keys(currentDict)) {
            dict[key] = currentDict[key];
        }
        return dict;
    }

    public static manageDefaultDictionaryValueType<T>(type: { new (data: T): T; }, object: any, property: string): DictionaryItem<T> {
        if (object === undefined || object === null) {
            return {};
        }
        if (object[property] === undefined || object[property] === null) {
            return {};
        }

        const currentDict = object[property];
        const dict: DictionaryItem<T> = {};
        for (const key of Object.keys(currentDict)) {
            dict[key] = new type(currentDict[key]);
        }
        return dict;
    }


    public static manageDefaultArrayValue(object: any, property: string, defaultValue: any): any[] {
        if (object === undefined || object === null) {
            return [];
        }
        if (object[property] === undefined || object[property] === null) {
            return [];
        }

        object[property].forEach((element: any, index: number, array: any[]) => {
            if (element === undefined || element === null) {
                array[index] = defaultValue;
            }
        });

        return [...object[property]];
    }

    public static manageDefaultArrayValueType<T>(type: { new (data: T): T; }, object: any, property: string): T[] {
        if (object === undefined || object === null) {
            return [];
        }
        if (object[property] === undefined || object[property] === null) {
            return [];
        }

        const arrays: T[] = [];
        for (const value of object[property]) {
            arrays.push(new type(value));
        }
        return arrays;
    }

    public static manageDefaultValue(object: any, property: string, defaultValue: any): any {
        if (object === undefined || object === null) {
            return defaultValue;
        }
        if (object[property] === undefined || object[property] === null) {
            return defaultValue;
        }

        return object[property];
    }

    public static manageDefaultValueType<T>(type: { new (data: T): T; }, object: any, property: string, defaultValue: T): T {
        if (object === undefined || object === null) {
            return defaultValue;
        }
        if (object[property] === undefined || object[property] === null) {
            return defaultValue;
        }

        return new type(object[property]);
    }
}
