import http from '@ohos.net.http';
import m from "../g/h";
import { WAVersion } from "../Constants";
import { d1 } from "./m";
import { DropCollectionModel } from "./v";
import { DEBUG } from "../../../../a";
export function o4(c6) {
    const d6 = parseInt(c6, 10);
    switch (d6) {
        case 1000: return "Success (1000)";
        case 1008: return "Pressure (1008)";
        case 1001:
        case 1003:
        case 1004:
        case 1005:
        case 1006:
        case 1009:
        case 1010:
        case 1015:
        case 1016: return "Drop (1001, 1003-1006, 1009-1010, 1015-1016)";
        case 1002:
        case 1007:
        case 1012: return "Retry (1002, 1007, 1012)";
        case 1013:
        case 1014: return "Strategy (1013, 1014)";
        default: return "Unknown";
    }
}
export default class FlushRequest {
    constructor(deviceInfo, appInfo) {
        this.o2 = false;
        this.deviceInfo = deviceInfo;
        this.appInfo = appInfo;
    }
    q2(x5, y5, events) {
        let properties = this.appInfo.toRecord();
        properties["wa_app_id"] = x5;
        properties["sub_app_id"] = y5;
        properties["dataList"] = events.map(event => event.toRecord());
        let z5 = this.deviceInfo.toRecord();
        const keys = Object.keys(z5);
        for (let b6 = 0; b6 < keys.length; b6++) {
            const key = keys[b6];
            const value = z5[key];
            properties[key] = value;
        }
        return JSON.stringify(properties);
    }
    async i2(y4, z4, identifier, events, a5 = "/wa-codcs/event-data-collect", b5 = 3) {
        return new Promise((d5, e5) => {
            let f5 = http.createHttp();
            let body = this.q2(y4, z4, events);
            if (DEBUG) {
                m.d('Sending: ' + body);
            }
            else {
                m.i('Sending: ' + events.toString());
            }
            let g5 = d1.s2(identifier);
            const h5 = a5;
            let url = this.t2(g5, h5);
            m.i("Sending to " + url);
            const i5 = (q5, data, r5) => {
                return new Promise((t5, u5) => {
                    const v5 = o4(q5.code);
                    m.i(`bizCode: ${v5}`);
                    switch (v5) {
                        case "Success (1000)":
                            m.i('API success');
                            t5(data);
                            break;
                        case "Pressure (1008)":
                            m.i('API success with pressure');
                            t5(data);
                            break;
                        case "Drop (1001, 1003-1006, 1009-1010, 1015-1016)":
                            m.i(`API drop (code ${q5.code})`);
                            let w5 = new DropCollectionModel(y4, z4, data.responseCode.toString(), h5, q5.code, q5.msg, "0", events.length.toString(), this.appInfo.app_version);
                            this.u2(g5, w5);
                            t5(data);
                            break;
                        case "Retry (1002, 1007, 1012)":
                            m.i(`API retry (code ${q5.code})`);
                            u5(new Error(`Retry (code ${q5.code})`));
                            break;
                        case "Strategy (1013, 1014)":
                            if (r5) {
                                m.i(`API strategy (code ${q5.code})`);
                                this.o2 = false;
                                u5(new Error(`Strategy (code ${q5.code})`));
                            }
                            else {
                                m.i(`API drop (code ${q5.code})`);
                                t5(data);
                            }
                            break;
                        default:
                            m.e(`API Unknown code (code ${q5.code})`);
                            t5(data);
                            break;
                    }
                });
            };
            f5.request(url, {
                method: http.RequestMethod.POST,
                header: {
                    'Content-Type': 'application/json',
                    'post_time': Date.now().toString(),
                    'wa_version': WAVersion,
                    "retry": "0",
                    "wa_app_id": y4,
                    "sub_app_id": z4,
                    "post_encode": "single",
                    "wa_batch_size": "1"
                },
                extraData: body,
                connectTimeout: 10000,
                readTimeout: 10000,
            }, (err, data) => {
                if (!err) {
                    m.i('Response Result:' + JSON.stringify(data.result));
                    m.i('Response code:' + JSON.stringify(data.responseCode));
                    d1.v2(identifier, data.responseCode);
                    if (data.responseCode >= 300) {
                        let p5 = new DropCollectionModel(y4, z4, data.responseCode.toString(), h5, data.responseCode.toString(), data.responseCode.toString(), "0", events.length.toString(), this.appInfo.app_version);
                        this.u2(g5, p5);
                    }
                    if (typeof data.result === 'string') {
                        try {
                            const m5 = JSON.parse(data.result);
                            i5(m5, data, this.o2)
                                .then(d5)
                                .catch((error) => {
                                if (b5 > 0 && error.message === `Retry (code ${m5.code})`) {
                                    m.d(error.message + `, remain count: ${b5 - 1}`);
                                    setTimeout(() => {
                                        m.d(`Real retry`);
                                        this.i2(y4, z4, identifier, events, a5, b5 - 1)
                                            .then(d5, e5);
                                    }, 1000);
                                }
                                else {
                                    m.d(`retries count exceeds`);
                                    e5(error);
                                }
                            });
                        }
                        catch (error) {
                            e5(error);
                        }
                    }
                    else {
                        e5(new Error(`data.result not string ${data.result})`));
                    }
                }
                else {
                    m.i('error:' + JSON.stringify(err));
                    let l5 = new DropCollectionModel(y4, z4, err.code.toString(), h5, err.code.toString(), err.message, "0", events.length.toString(), this.appInfo.app_version);
                    this.u2(g5, l5);
                    e5(err);
                }
                f5.destroy();
            });
        });
    }
    u2(s4, t4) {
        let u4 = http.createHttp();
        let url = this.t2(s4, '/wa-codcs/fail-data-collect');
        m.w("[report] Sending to " + url);
        m.w("diagnosticData:" + JSON.stringify(t4));
        u4.request(url, {
            method: http.RequestMethod.POST,
            header: {
                'Content-Type': 'application/json',
                'post_time': Date.now().toString(),
                'wa_version': WAVersion,
                "retry": "0",
                "wa_app_id": t4.wa_app_id,
                "sub_app_id": t4.sub_app_id,
                "post_encode": "single",
                "wa_batch_size": "1"
            },
            extraData: JSON.stringify(t4),
            connectTimeout: 10000,
            readTimeout: 10000,
        }, (err, data) => {
            if (!err) {
                m.i('[report] Result:' + JSON.stringify(data.result));
                m.i('[report] code:' + JSON.stringify(data.responseCode));
                if (typeof data.result === 'string') {
                    try {
                        const w4 = JSON.parse(data.result);
                        const x4 = o4(w4.code);
                        m.i(`[report] bizCode: ${x4}`);
                    }
                    catch (error) {
                        m.i(`[report] error: ${error}`);
                    }
                }
                else {
                    m.i(`[report] data.result not string: ${data.result}`);
                }
            }
            else {
                m.i('[report] error:' + JSON.stringify(err));
            }
            u4.destroy();
        });
    }
    w2(data) {
    }
    t2(base, path, p4) {
        try {
            let url = base.endsWith('/') ? base.slice(0, -1) : base;
            url += path.startsWith('/') ? path : `/${path}`;
            if (p4) {
                const q4 = Object.keys(p4)
                    .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(p4[key])}`)
                    .join('&')
                    .replace(/\+/g, '%2B');
                url += `?${q4}`;
            }
            return url;
        }
        catch (error) {
            m.e(`buildURL error: ${error}`);
            return null;
        }
    }
}
