package com.cnd3b.utility.obs;

import com.huaweicloud.sdk.ces.v1.CesClient;
import com.huaweicloud.sdk.ces.v1.model.Datapoint;
import com.huaweicloud.sdk.ces.v1.model.ShowMetricDataRequest;
import com.huaweicloud.sdk.ces.v1.model.ShowMetricDataResponse;
import com.huaweicloud.sdk.ces.v1.region.CesRegion;
import com.huaweicloud.sdk.core.auth.BasicCredentials;
import com.huaweicloud.sdk.core.auth.ICredential;
import com.huaweicloud.sdk.core.exception.ConnectionException;
import com.huaweicloud.sdk.core.exception.ServiceResponseException;
import com.cnd3b.common.data.Rows;
import com.cnd3b.common.data.SQLFactory;
import com.cnd3b.common.data.db.DBConnect;
import com.cnd3b.common.parameter.parameter;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

public class BucketCESManage {
    protected String bucketname;
    protected CesClient cesClient;
    protected ArrayList<String> sqllist1;
    protected ArrayList<String> sqllist2;
    protected long fromtime;
    protected long totime;
    protected  String yeaterday;

    public BucketCESManage(String siteid) {
        this.bucketname = siteid.toLowerCase();
        ICredential auth = new BasicCredentials().withAk(parameter.Bucket_ak()).withSk(parameter.Bucket_sk());
        cesClient = CesClient.newBuilder().withCredential(auth).withRegion(CesRegion.valueOf(parameter.Bucket_location())).build();
        sqllist1 = new ArrayList<>();
        sqllist2 = new ArrayList<>();
    }

    public void getData() {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, -1);
        yeaterday = new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime());
        DBConnect dbConnect = new DBConnect();
        Rows rows = dbConnect.runSqlQuery("select * from TOBSDATALOG where siteid='" + bucketname + "' and convert(varchar(10),fdate,120)='" + yeaterday + "'");

        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        fromtime = calendar.getTimeInMillis();
        calendar.add(Calendar.DATE, 1);
        totime = calendar.getTimeInMillis();
        if (rows.size()<6) {
            getDownload_traffic();
            if (!sqllist1.isEmpty()) {
                dbConnect.runSqlUpdate(sqllist1);
            }
            getUpload_traffic();
            if (!sqllist2.isEmpty()) {
                dbConnect.runSqlUpdate(sqllist2);
            }
        }
    }

    /**
     * 总下载流量
     */
    private void getDownload_traffic() {
        ShowMetricDataRequest request = new ShowMetricDataRequest();
        request.withNamespace("SYS.OBS");
        request.withMetricName("download_traffic");
        request.withDim0("bucket_name," + bucketname);
        request.withFilter(ShowMetricDataRequest.FilterEnum.fromValue("sum"));
        request.withPeriod(14400);
        request.withFrom(fromtime);
        request.withTo(totime);
        try {
            ShowMetricDataResponse response = cesClient.showMetricData(request);
            List<Datapoint> list = response.getDatapoints();
            if (!list.isEmpty()) {
                for (Datapoint datapoint : list) {
                    double fdownloadbytes = datapoint.getSum();
                    long time = datapoint.getTimestamp();

                    Calendar datetime = Calendar.getInstance();
                    datetime.setTimeInMillis(time);
                    String fdate = new SimpleDateFormat("yyyy-MM-dd").format(datetime.getTime());
                    String fdatetime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(datetime.getTime());

                    SQLFactory factory = new SQLFactory(this, "数据流出量日志更新");
                    factory.addParameter("siteid", bucketname.toUpperCase());
                    factory.addParameter("ftimestamp", time);
                    factory.addParameter("fdate", fdate);
                    factory.addParameter("fdatetime", fdatetime);
                    factory.addParameter("fdownloadbytes", fdownloadbytes);
                    sqllist1.add(factory.getSQL());
                }
            }
        } catch (ConnectionException e) {
            e.printStackTrace();
        } catch (ServiceResponseException e) {
            e.printStackTrace();
            System.out.println(e.getHttpStatusCode());
            System.out.println(e.getErrorCode());
            System.out.println(e.getErrorMsg());
        }
    }

    /**
     * 总上传流量
     */
    private void getUpload_traffic() {
        ShowMetricDataRequest request = new ShowMetricDataRequest();
        request.withNamespace("SYS.OBS");
        request.withMetricName("upload_traffic");
        request.withDim0("bucket_name," + bucketname);
        request.withFilter(ShowMetricDataRequest.FilterEnum.fromValue("sum"));
        request.withPeriod(14400);
        request.withFrom(fromtime);
        request.withTo(totime);
        try {
            ShowMetricDataResponse response = cesClient.showMetricData(request);
            List<Datapoint> list = response.getDatapoints();
            if (!list.isEmpty()) {
                for (Datapoint datapoint : list) {
                    double fuploadbytes = datapoint.getSum();
                    long time = datapoint.getTimestamp();

                    Calendar datetime = Calendar.getInstance();
                    datetime.setTimeInMillis(time);

                    String fdate = new SimpleDateFormat("yyyy-MM-dd").format(datetime.getTime());
                    String fdatetime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(datetime.getTime());

                    SQLFactory factory = new SQLFactory(this, "数据上传量日志更新");
                    factory.addParameter("siteid", bucketname.toUpperCase());
                    factory.addParameter("ftimestamp", time);
                    factory.addParameter("fdate", fdate);
                    factory.addParameter("fdatetime", fdatetime);
                    factory.addParameter("fuploadbytes", fuploadbytes);
                    sqllist2.add(factory.getSQL());
                }
            }
        } catch (ConnectionException e) {
            e.printStackTrace();
        } catch (ServiceResponseException e) {
            e.printStackTrace();
            System.out.println(e.getHttpStatusCode());
            System.out.println(e.getErrorCode());
            System.out.println(e.getErrorMsg());
        }
    }
}
