import Review from '../models/Review.js'
import cheerio, { html } from "cheerio";
import jschardet from 'jschardet'
import iconv from 'iconv'
import fs from 'fs'
import axios from 'axios';
import { nextTick } from 'process';
import { response } from 'express';
const Iconv = iconv.Iconv

const search = async (req, res, next) => {
    const url = "https://www.google.com/search?q=" + encodeURI(req.params.search) + "+site%3Atistory.com&page_no=1"
    let reviews = []
    try {
        axios.get(url)
            .then((response1) => {
                const $1 = cheerio.load(response1.data);
                $1('.kCrYT').each(function (i) {
                    const searchParams = new URLSearchParams($1(this).find('a').attr('href'));
                    const title = $1(this).find('h3').text()
                    const link = searchParams.get("/url?q")
                    const summary = $1(this).find('.s3v9rd').find('.s3v9rd').text()

                    if (title) {
                        reviews[i] = { title: title, link: link, }
                    } else if (summary) {
                        reviews[i - 1] = { ...reviews[i - 1], summary: summary }
                        reviews = reviews.filter(e => e)
                    }
                    // const review = new Review(reviews).save()
                })
                res.send(reviews)
            })
    } catch (error) {

        // reviews.forEach((review) => {
        //     axios.get(review.link)
        //         .then((response2) => {
        //             const $2 = cheerio.load(response2.data);
        //             let content = ''
        //             if ($2('.tt_article_useless_p_margin').text()) {
        //                 content = $2('.tt_article_useless_p_margin').text()
        //             }
        //             review = { content: content }
        //             console.log("dkssud")
        //         })
        //         console.log("dkssud")
        // })
        // console.log(content)
        res.status(500).send(error)
    }
}
const getReview = async (link) => {
    let content = '없음'
    const res = await axios.get(link)
    const $2 = cheerio.load(res.data);
    if ($2('.tt_article_useless_p_margin').text()) {
        content = $2('.tt_article_useless_p_margin').text()
    }
    console.log(content, "getReiview")
    return content
}

export default { search, getReview }