package com.hzjt.handler;

import com.hzjt.domain.Ftp;
import com.hzjt.domain.Traffalarmrecord;
import com.hzjt.domain.TransferResult;
import com.hzjt.util.DateUtils;
import com.hzjt.util.FTPUtil;
import com.hzjt.util.ThreadPoolUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

@Slf4j
public class FileTransferManager {
    private static  CompletionService<TransferResult> completionService  = new ExecutorCompletionService<TransferResult>(ThreadPoolUtil.getPool());

    /**
     * @param transferRecord
     * @param ftp
     * @param basePath
     * @return
     * @throws Exception
     */
    public static List<TransferResult> transferFile(final Map<String,Object> transferRecord , final Ftp ftp, final String basePath) throws Exception {
        Integer  ret = 0 ;
        final Long recordid = Long.parseLong(transferRecord.get("recordid").toString());
        int count = 0 ;
        for(String key : transferRecord.keySet()){
            if(key.equals("img1path") || key.equals("img2path")
                    || key.equals("img3path") || key.equals("img4path")
                    || key.equals("img5path")){
                final String url = transferRecord.get(key).toString() ;
                count++;
                completionService.submit(()->{
                        TransferResult result = new TransferResult(recordid,key,url,"",false);
                        try {
                            String filesuff =  "videopath".equals(key) ? ".mp4": ".jpg";

                            HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
                            //延迟连接
                            connection.setReadTimeout(2000);
                            connection.setConnectTimeout(3000);
                            connection.setRequestMethod("GET");
                            /// System.out.println("connection.getResponseCode:" + connection.getResponseCode() );
                            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                                InputStream inputStream = connection.getInputStream();
                                log.info("url:",url , " --- "+"key:",key);
                                String pname = DateUtils.formatCurrDayNoSign() + "_"+recordid+"_0000_"+key.replace("path","");
                                String fileName = pname +filesuff;
                                String ftputl = FTPUtil.getFtpUrl(ftp) + basePath + "/" + fileName;
                                boolean  r = FTPUtil.uploadFile(ftp,basePath, fileName,inputStream);
                                result.setResult(r);
                                if(r){
                                    result.setImgpath(ftputl);
                                }
                                log.info("callable thread:" +result.toString());
                            }else{
                                log.error("connection code: "+connection.getResponseCode() +" ," +result.toString());
                            }
                        } catch (IOException e) {
                            System.out.println(e.toString());
                            log.error(e.toString());
                        }

                        return result;
                });
            }
        }
        List<TransferResult> listret = new ArrayList<>();
        for (int i = 0; i < count ; i++) {
            listret.add(completionService.poll(10, TimeUnit.SECONDS).get());
        }
        return listret;
    }



    public static void fetchUrlsFromRecord(Traffalarmrecord record , Map<String,Object> transferRecord){
        if(record ==null ||  record.getRecordid()==null){
            return;
        }

        transferRecord.put("recordid" , record.getRecordid());

        if(record.getImg1path() == null &&  record.getImg1urlfrom() != null){
            transferRecord.put("img1path" , record.getImg1urlfrom());
        }

        if(record.getImg2path() == null &&  record.getImg2urlfrom() != null){
            transferRecord.put("img2path" , record.getImg2urlfrom());
        }

        if(record.getImg3path() == null &&  record.getImg3urlfrom() != null){
            transferRecord.put("img3path" , record.getImg3urlfrom());
        }

        if(record.getImg4path() == null &&  record.getImg4urlfrom() != null){
            transferRecord.put("img4path" , record.getImg4urlfrom());
        }

        if(record.getImg5path() == null &&  record.getImg5urlfrom() != null){
            transferRecord.put("img5path" , record.getImg5urlfrom());
        }

        if(record.getVideopath() ==null &&  record.getVideourlfrom() != null){
            transferRecord.put("videopath" , record.getVideourlfrom());
        }
    }

    public static Traffalarmrecord traffAlarmRecordUrlUpdate(List<TransferResult> results) throws  Exception{
        Traffalarmrecord record = new Traffalarmrecord();
        for (TransferResult result : results){
            record.setRecordid(result.getRecordid());
            if(result.getResult()){
                switch (result.getPathvalue()){
                    case "img1path" :
                        record.setImg1path(result.getImgpath());
                        break;
                    case "img2path"  :
                        record.setImg2path(result.getImgpath());
                        break;
                    case "img3path"  :
                        record.setImg3path(result.getImgpath());
                        break;
                    case "img4path"  :
                        record.setImg4path(result.getImgpath());
                        break;
                    case "img5path"  :
                        record.setImg5path(result.getImgpath());
                        break;
                    case "videopath"  :
                        record.setVideopath(result.getImgpath());
                        break;
                    default :
                        log.info("unknow pathvalue"+ result.getPathvalue());
                        break;
                }
            }
        }
        return record;
    }


//    public static void main(String[] args) {
//        urls.add("http://img63.ddimg.cn/2019/12/18/2019121819114913026.jpg");
//        urls.add("http://img62.ddimg.cn/2019/12/18/201912181655214974.jpg");
//        urls.add("http://img61.ddimg.cn/2019/12/18/2019121816294684833.jpg");
//        urls.add("http://img63.ddimg.cn/2019/12/18/2019121819121717247.jpg");
//        urls.add("http://img62.ddimg.cn/2019/12/18/201912181655214974.jpg");
//    }


}

