const cheerio = require("cheerio")
    , client = require('./Client');


class Product {

    constructor() {
        this.data = {}
        this.amazon = null
    }

    async fetch(amazon, asin) {
        this.amazon = amazon;

        let args = [{ amazon: this.amazon, asin: asin, call: 'productDetail', resolver: 'parseHtmlDetail' },
        { amazon: this.amazon, asin: asin, call: 'offerListing', resolver: 'parseHtmlOfferListing' }]
        let fetchPromises = args.map(async args => {
            return await client.request(args)
        })

        for (let k in fetchPromises) {            
            await fetchPromises[k].then(body => this[args[k].resolver](body))
        }
        this.data.asin = asin
        return this.data
    }

    parseHtmlDetail(body) {
        let $ = cheerio.load(body)
        this.data.title = $('#productTitle').text().trim()
        let merchant = $('#merchant-info a');
        if (!merchant.length) {
            merchant = $('#merchant-info');
        }
        this.data.seller = {
            title: merchant.text().replace('에서 판매하고 배송합니다.', '').replace('주문 처리', '').trim(),
            link: merchant.attr('href')
        }

        this.data.img = $('#landingImage').attr('src')
        this.data.description = this.description(this.amazon, $)
        this.data.category = this.category(this.amazon, $)
        this.data.price = this.price(this.amazon, $)
        this.data.colors = this.colors(this.amazon, $)
        this.data.colorsASIN = this.colorsASIN(this.amazon, $)
    }

    description(amazon, $) {
        return {
            content: $('#aplus').html(),
            spec: $('#descriptionAndDetails').html(),
            videos: function () {
                if ($('#vse-rel-videos-carousel ol li a').length) {
                    return {
                        link: amazon.us.data.url + $('#vse-rel-videos-carousel ol li a').eq(0).attr('href'),
                        title: $('#vse-rel-videos-carousel ol li a div.vse-video-content .vse-video-title-text').eq(0).text().trim()
                    }
                } else return {}
            }()
        }
    }

    parseHtmlOfferListing(body) {
        let $ = cheerio.load(body)
        let stock = $('#olpOfferList .a-row.olpOffer').length;
        let price = $('#olpOfferList div.a-column.a-span2.olpPriceColumn').last().find('span').text().trim();
        // let seller = $('#olpOfferList .olpSellerName').last().find('span a').text().trim();
        // let sellerLink = $('#olpOfferList .olpSellerName').last().find('span a').attr('href');
        this.data.stock = stock;
        this.data.price = price;
        // this.data.seller = { title: seller, link: sellerLink }
    }

    category(amazon, $) {
        let categoryPath = []
        $('#wayfinding-breadcrumbs_feature_div li a').map((k, n) => {
            categoryPath.push({ title: $(n).text().trim(), link: amazon.us.data.url + $(n).attr('href') })
        })
        return categoryPath
    }

    price(amazon, $) {
        let price;
        price = $('#olp-upd-new > span > a').eq(0).text().trim()
        if (price) {
            if (price.split('$').length == 2) {
                return '$' + price.split('$')[1]
            }
        }
        price = $('#priceblock_ourprice').text().trim()
        if (price) return price
    }

    colors(amazon, $) {
        let colors = []
        $('li[id^=color_name_]').map((k, n) => {
            colors.push({
                img: $(n).find('img').attr('src'),
                title: $(n).find('img').attr('alt'),
            })
        })
        return colors
    }
    colorsASIN(amazon, $) {
        let colorsASIN = []
        $('li[id^=color_name_]').map((k, n) => {
            let asin = $(n).attr('data-defaultasin');
            if (!asin) {
                asin = $(n).attr('data-dp-url').split('/')[2];
            }
            colorsASIN.push(asin)
        })
        return colorsASIN
    }

}

module.exports = Product;