package com.lingniu.ingest.tdenginehistory;

import java.util.List;
import java.util.Arrays;

public final class TdengineHistoryStatements {

    private static final String RAW_FRAME_COLUMNS = "ts, frame_id, received_at, message_id, sub_type, event_time, "
            + "raw_uri, checksum, raw_size_bytes, parse_status, parse_error, peer, metadata_json, parsed_json";
    private static final String RAW_FRAME_PLACEHOLDERS = "?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?";

    private static final String LOCATION_COLUMNS = "ts, fact_id, frame_id, received_at, longitude, latitude, "
            + "altitude_m, speed_kmh, direction_deg, alarm_flag, status_flag, total_mileage_km, raw_uri";
    private static final String LOCATION_PLACEHOLDERS = "?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?";

    private final TdengineHistorySchema schema;

    public TdengineHistoryStatements(TdengineHistorySchema schema) {
        if (schema == null) {
            throw new IllegalArgumentException("schema must not be null");
        }
        this.schema = schema;
    }

    public TdengineBatchStatement rawFrame(TdengineRawFrameRow row) {
        String table = schema.rawFrameTable(row.protocol(), row.vehicleKey());
        return new TdengineBatchStatement(
                "CREATE TABLE IF NOT EXISTS " + table + " USING raw_frames TAGS ("
                        + tags(row.protocol(), row.vehicleKey(), row.vin(), row.phone()) + ")",
                "INSERT INTO " + table + " (" + RAW_FRAME_COLUMNS + ") VALUES (" + RAW_FRAME_PLACEHOLDERS + ")",
                values(
                        row.ts(), row.frameId(), row.receivedAt(), row.messageId(), row.subType(),
                        row.eventTime(), row.rawUri(), row.checksum(), row.rawSizeBytes(), row.parseStatus(),
                        row.parseError(), row.peer(), row.metadataJson(), row.parsedJson()
                )
        );
    }

    public TdengineBatchStatement location(TdengineLocationRow row) {
        String table = schema.locationTable(row.protocol(), row.vehicleKey());
        return new TdengineBatchStatement(
                "CREATE TABLE IF NOT EXISTS " + table + " USING vehicle_locations TAGS ("
                        + tags(row.protocol(), row.vehicleKey(), row.vin(), row.phone()) + ")",
                "INSERT INTO " + table + " (" + LOCATION_COLUMNS + ") VALUES (" + LOCATION_PLACEHOLDERS + ")",
                values(
                        row.ts(), row.factId(), row.frameId(), row.receivedAt(), row.longitude(), row.latitude(),
                        row.altitudeM(), row.speedKmh(), row.directionDeg(), row.alarmFlag(), row.statusFlag(),
                        row.totalMileageKm(), row.rawUri()
                )
        );
    }

    private static String tags(String protocol, String vehicleKey, String vin, String phone) {
        return quote(protocol) + ", " + quote(vehicleKey) + ", " + quote(vin) + ", " + quote(phone);
    }

    private static String quote(String value) {
        return "'" + (value == null ? "" : value.replace("'", "''")) + "'";
    }

    private static List<Object> values(Object... values) {
        return Arrays.asList(values);
    }
}
