package com.zhiqiyun.open.core.spiders;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zhiqiyun.open.core.models.sentiment.SentimentSpiderSiteRule;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.processor.PageProcessor;

import java.net.URL;
import java.util.*;

@Slf4j
public class WeiboPageProcessor implements PageProcessor {

    private final Site site;

    private final SentimentSpiderSiteRule rule;


    public WeiboPageProcessor(SentimentSpiderSiteRule rule) {
        this.rule = rule;
        this.site = Site.me();
        this.site.setUseGzip(true);
        this.site.setRetryTimes(3);
        this.site.setSleepTime(1000);
    }

    @Override
    public void process(Page page) {
        try {
            URL url = new URL(page.getUrl().get());
            Map<String, String> queryMap = this.getMap(url.getQuery());
            List<String> listQueries = new ArrayList<>();
            for (String key : queryMap.keySet()) {
                String value = queryMap.get(key);
                if ("max_id".equals(key)) {
                    int v = Integer.parseInt(value);
                    value = String.valueOf(v + 1);
                }
                listQueries.add(String.format("%s=%s", key, value));
            }
            String queryString = StringUtils.join(listQueries, "&");

            log.info("max_id>>>>>>>>>{}", queryMap.get("max_id"));

            page.addTargetRequest(String.format("https://weibo.com/ajax/feed/hottimeline?%s", queryString));

            String text = page.getRawText();
            JSONObject jsonObject = JSON.parseObject(text);
            int ok = jsonObject.getInteger("ok");
            if (ok == 1) {
                List<String> listFragments = new ArrayList<>();
                List<JSONObject> list = jsonObject.getJSONArray("statuses").toJavaList(JSONObject.class);
                List<String> listTitles = new ArrayList<>();
                List<String> listIds = new ArrayList<>();
                List<String> listCreatedAts = new ArrayList<>();
                for (JSONObject o : list) {
                    listCreatedAts.add(o.getString("created_at"));
                    listIds.add(o.getString("id"));
                    listTitles.add(o.getString("source"));
                    JSONObject longText = o.getJSONObject("longText");
                    if (longText != null) {
                        listFragments.add(longText.getString("longTextContent"));
                    } else {
                        listFragments.add(o.getString("text_raw"));
                    }

                }


                page.putField("listCreatedAts", JSON.toJSONString(listCreatedAts));
                page.putField("listIds", JSON.toJSONString(listIds));
                page.putField("listTitles", JSON.toJSONString(listTitles));
                page.putField("listFragments", JSON.toJSONString(listFragments));
            } else {
                page.setSkip(true);
            }
        } catch (Exception e) {
            log.error("", e);
            page.setSkip(true);
        }
    }

    @Override
    public Site getSite() {
        return this.site;
    }

    public Map<String, String> getMap(String urlparam) {
        Map<String, String> map = new HashMap<>();
        String[] param = urlparam.split("&");
        for (String keyvalue : param) {
            String[] pair = keyvalue.split("=");
            if (pair.length == 2) {
                map.put(pair[0], pair[1]);
            }
        }
        return map;
    }
}
