package com.tzld.piaoquan.ad.engine.service.predict.container;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.CredentialsProvider;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.model.CopyObjectResult;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.PutObjectResult;
import com.tzld.piaoquan.ad.engine.commons.redis.AlgorithmRedisHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Date;
import java.util.Random;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Component
public class RandWContainer {
    private final static Logger log = LoggerFactory.getLogger(RandWContainer.class);

    @Autowired
    private AlgorithmRedisHelper redisHelper;

    private static final int SCHEDULE_PERIOD = 10;
    private static final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

    String randWKey = "ad:engine:random:w";

    OSS client;

    public static Integer randW=0;

    private static Random random=new Random();
    private Date cacheDate;

    @PostConstruct
    private void init(){
        final Runnable task = new Runnable() {
            public void run() {
                try {
                    loadAndCalIfNeed();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        };
        scheduler.scheduleAtFixedRate(task, 0, SCHEDULE_PERIOD, TimeUnit.SECONDS); // 60分钟
    }


    private void loadAndCalIfNeed(){
        loadRandW();
        Date now=new Date(System.currentTimeMillis()-60*60*1000);
        if(cacheDate==null||now.after(cacheDate)){
            calNewRandomW();
            writeToRedis();
        }
    }

    private void calNewRandomW() {
        randW=random.nextInt(100);
    }

    private void writeToRedis(){
        //先不考虑各种更新失败及重复更新问题。
        redisHelper.set(randWKey,randW.toString()+"_"+System.currentTimeMillis(),0);
    }

    private void loadRandW(){
        try {
            String str=redisHelper.getString(randWKey);
            if(str==null) return;
            String[] arr=str.split("_");
            randW=Integer.parseInt(arr[0]);
            this.cacheDate=new Date(Long.parseLong(arr[1]));
        }catch (Exception e){
            log.error("svc=load_randomW status=failed error={}", Arrays.toString(e.getStackTrace()));
            e.printStackTrace();
        }
    }

    public static Integer getRandW(){
        return randW;
    }

}
