import { Meteor } from 'meteor/meteor';
import { check } from 'meteor/check';
import { HTTP } from 'meteor/http';
import Brands from '../collections/brands.js';

import { Logger } from 'meteor/ostrio:logger';
import { LoggerFile } from 'meteor/ostrio:loggerfile';

var log = new Logger();
(new LoggerFile(log)).enable();

Meteor.methods({
    'getBrands' () {
        debugger
        this.unblock();
        if (this.userId) {
            try {

                Meteor.settings.enableDebug ? log.debug("getBrands() => start get brands list", {}, Meteor.user().username) : '';
                const result = HTTP.call('GET', `${Meteor.settings.worklistUrl}/HISIntegration.svc/rest/GetHISBrandsRest`);
                Meteor.settings.enableDebug ? log.debug("getBrands() => brands list have been fetched", result, Meteor.user().username) : '';
                let brandsHttpResult = JSON.parse(result.content);

                Meteor.settings.enableDebug ? log.debug("getBrands() => start remove old brands from db", {}, Meteor.user().username) : '';

                Brands.remove({});

                Meteor.settings.enableDebug ? log.debug("getBrands() => old brands have been removed from db", {}, Meteor.user().username) : '';

                Meteor.settings.enableDebug ? log.debug("getBrands() => start add new brands to db", {}, Meteor.user().username) : '';
                brandsHttpResult.Items.forEach((brand) => {
                    Brands.insert({
                        ...brand
                    });
                });

                Meteor.settings.enableDebug ? log.debug("getBrands() => new brands  have been added to db", {}, Meteor.user().username) : '';
                return true
            } catch (e) {
                log.error("getBrands Error", e, Meteor.user().username);
                throw new Meteor.Error(500, "error");
            }
        } else {
            log.error("getBrands() => no loggined user for getBrands");
            throw new Meteor.Error(500, "error");
        }
    },
    "getBrandsName" () {

        this.unblock();
        if (this.userId) {
            try {
                const result = HTTP.call('GET', `${Meteor.settings.worklistUrl}/HISIntegration.svc/rest/GetHISBrandsRest`);
                let brandsHttpResult = JSON.parse(result.content);
                return brandsHttpResult.Items.map(brandObj => {
                    return brandObj.Name
                })
            } catch (e) {
                // Got a network error, timeout, or HTTP error in the 400 or 500 range.
                throw new Meteor.Error(500, "error");
            }
        }

    }
});
Meteor.settings.enableDebug ? log.debug(`endof barnads`) : '';