package com.ycwl.basic.device.operator;

import cn.hutool.crypto.digest.MD5;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ycwl.basic.device.entity.common.FileObject;
import com.ycwl.basic.device.entity.wvp_active.WvpActiveStorageConfig;
import com.ycwl.basic.storage.exceptions.StorageConfigException;
import com.ycwl.basic.storage.exceptions.StorageUnsupportedException;
import org.apache.commons.lang3.StringUtils;

import java.net.URI;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class WvpActiveStorageOperator extends ADeviceStorageOperator {

    public WvpActiveStorageOperator(String configJson) {
        loadConfig(configJson);
    }
    private WvpActiveStorageConfig config;

    @Override
    public void loadConfig(String configJson) {
        this.config = JSON.parseObject(configJson, WvpActiveStorageConfig.class);
    }

    @Override
    public List<FileObject> getFileListByDtRange(Date startDate, Date endDate) {
        return listDirByDtRange(startDate, endDate);
    }

    @Override
    public boolean removeFilesBeforeDate(Date date) {
        return true;
    }


    private String token;
    private String getToken() {
        if (this.token != null) {
            return this.token;
        }
        String url = this.config.getHost() + "/api/user/login";
        Map<String, Object> params = new HashMap<>();
        params.put("username", this.config.getLoginName());
        String password = MD5.create().digestHex(this.config.getLoginPassword());
        params.put("password", password);
        String jsonResult = HttpUtil.get(url, params);
        JSONObject result = JSON.parseObject(jsonResult);
        if (result.getInteger("code") == 0) {
            JSONObject data = result.getJSONObject("data");
            this.token = data.getString("accessToken");
            return this.token;
        } else {
            throw new StorageConfigException("获取token失败，原因为：" + result.getString("msg"));
        }
    }
    public List<FileObject> listDirByDtRange(Date startDate, Date endDate) {
        SimpleDateFormat normalDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String url = this.config.getHost() + "/api/cloud/record/list";
        Map<String, Object> params = new HashMap<>();
        params.put("app", this.config.getApp());
        params.put("stream", this.config.getStream());
        params.put("startTime", normalDateFormat.format(startDate));
        params.put("endTime", normalDateFormat.format(endDate));
        params.put("page", 1);
        params.put("count", 100);
        String jsonResult = HttpRequest.get(url).form(params).header("Access-Token", getToken()).execute().body();
        JSONObject result = JSON.parseObject(jsonResult);
        if (result.getInteger("code") == 0) {
            JSONObject data = result.getJSONObject("data");
            List<JSONObject> recordList = data.getJSONArray("list").toJavaList(JSONObject.class);
            return recordList.stream()
                    .map(record -> {
                        FileObject object = new FileObject();
                        object.setName(record.getString("id"));
                        object.setPath(record.getString("folder"));
                        object.setUrl(getUrlForDownload(record.getInteger("id")));
                        object.setNeedDownload(true);
                        object.setCreateTime(new Date(record.getLongValue("startTime")));
                        object.setEndTime(new Date(record.getLongValue("endTime")));
                        return object;
                    })
                    .sorted(Comparator.comparing(FileObject::getCreateTime))
                    .collect(Collectors.toList());
        }
        return Collections.emptyList();
    }

    public String getUrlForDownload(int id) {
        // assume path is recordId
        String url = this.config.getHost() + "/api/cloud/record/play/path?recordId=" + id;
        String jsonResult = HttpRequest.get(url).header("Access-Token", getToken()).execute().body();
        JSONObject result = JSON.parseObject(jsonResult);
        if (result.getInteger("code") == 0) {
            JSONObject data = result.getJSONObject("data");
            String httpPath = data.getString("httpPath");
            if (StringUtils.isBlank(this.config.getZlmHost())) {
                return httpPath;
            }
            // 替换host
            URI uri = URI.create(httpPath);
            if (uri.getQuery() == null) {
                return this.config.getZlmHost() + uri.getPath();
            }
            return this.config.getZlmHost() + uri.getPath() + "?" + uri.getQuery();
        } else {
            throw new StorageUnsupportedException("获取播放地址失败，原因为：" + result.getString("msg"));
        }
    }

}
