/** @module endpoints/market **/

import request from 'request-promise-native';
import find from 'lodash/find';
import isObject from 'lodash/isObject';

import urlBuilder from '../utils/urlBuilder';

export function marketRoot () {
    return new Promise(function (res, rej) {
        const url = urlBuilder.market({ queryType: 'rootPrices' });
        const options = {
            url
        };

        request(options)
            .then(data => {
                res(JSON.parse(data));
            })
            .catch(e => {
                rej(e);
            });
    });
}

export function marketItemPrice (itemId) {
    console.log(`This is a costly request, please limit it's use. Best thing to do if you are making lots of requests is to cache the full rootPrices and look against it!`);
    return new Promise((res, rej) => {
        marketRoot()
            .then(data => {
                const item = find(data.items, ['type.id', itemId]);
                if(isObject(item)) {
                    res(item);
                } else {
                    rej(new Error(`Looks like there's an issue with us finding that item! Please double check the ID.`));
                }
            })
            .catch(e => {
                rej(e);
            });
    });
}

export function itemSellOrdersByRegion (itemId, regionId) {
    return new Promise((res, rej) => {
        const url = urlBuilder.market({ queryType: 'itemSellOrdersInRegion', itemId, regionId });
        const options = {
            url
        };

        request(options)
            .then(data => {
                res(JSON.parse(data));
            })
            .catch(e => {
                rej(e);
            });
    });
}

export function getItemTypes () {
    return new Promise((res, rej) => {
        const url = urlBuilder.market({ queryType: 'itemTypes'});
        const options = {
            url
        };

        request(options)
            .then(data => {
                res(JSON.parse(data));
            })
            .catch(e => {
                rej(e);
            });
    });
}

export function getItemType (itemId) {
    return new Promise((res, rej) => {
        const url = urlBuilder.market({ queryType: 'itemType', itemId });
        const options = {
            url
        };

        request(options)
            .then(data => {
                res(JSON.parse(data));
            })
            .catch(e => {
                rej(e);
            });
     });
}
