package com.inspect.patrol.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.inspect.base.core.exception.ServiceException;
import com.inspect.base.core.sftp.SftpClient;
import com.inspect.base.core.sftp.SftpUploadEntity;
import com.inspect.base.core.utils.HttpClientUtils;
import com.inspect.base.redis.service.RedisService;
import com.inspect.patrol.contants.AccessApiConstant;
import com.inspect.patrol.linkage.util.JsonUtil;
import com.inspect.patrol.model.SnapModel;

import java.io.InputStream;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class DeviceIntoService {
    @Value("${gwb.url}")
    private String deviceUrl;
    private final SftpClient sftpClient;
    private final RedisService redisService;
    private final Video2NvrComponent video2NvrComponent;
    private final String SNAP_PATH = "snap/";

    public DeviceIntoService(SftpClient sftpClient, RedisService redisService, Video2NvrComponent video2NvrComponent) {
        this.sftpClient = sftpClient;
        this.redisService = redisService;
        this.video2NvrComponent = video2NvrComponent;
    }

    public String snap(SnapModel snapModel) throws Exception {
        SftpUploadEntity sftpUploadEntity = new SftpUploadEntity();
        sftpUploadEntity.setFilePath(SNAP_PATH);
        (new Thread(() -> {
            snapModel.setSerial(this.video2NvrComponent.toNvrCode(snapModel.getPatrolDeviceCode()));
            String params = JsonUtil.json2Str(JSONObject.parseObject(JSONObject.toJSONString(snapModel)));

            InputStream in;
            try {
                in = HttpClientUtils.getStream(this.deviceUrl + AccessApiConstant.CHANNEL_SNAP, params);
            } catch (Exception var7) {
                var7.printStackTrace();
                throw new ServiceException("快照调取ivs失败！");
            }

            sftpUploadEntity.setInputStream(in);

            try {
                this.sftpClient.upload(sftpUploadEntity);
            } catch (Exception e) {
                e.printStackTrace();
                throw new ServiceException("快照上传失败！");
            }
        })).start();
        return sftpUploadEntity.getFileFullName();
    }

    public static void main(String[] args) {
    }
}
