/*
 * Copyright 2022 Igalia, S.L.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { v4 as uuidv4 } from 'uuid';

const DEFAULT_TARGET = "wss://localhost:8090";

// TODO: use an application token when needed
// currently using https://github.com/eclipse/kuksa.val/blob/master/kuksa_certificates/jwt/super-admin.json.token
const TEST_TOKEN = 
    'eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJrdWtzYS52YWwiLCJpc3MiOiJFY2xpcHNlIEtVS1NBIERldiIsImFkbWluIjp0cnVlLCJtb2RpZnlUcmVlIjp0cnVlLCJpYXQiOjE1MTYyMzkwMjIsImV4cCI6MTc2NzIyNTU5OSwia3Vrc2EtdnNzIjp7IioiOiJydyJ9fQ.p2cnFGH16QoQ14l6ljPVKggFXZKmD-vrw8G6Vs6DvAokjsUG8FHh-F53cMsE-GDjyZH_1_CrlDCnbGlqjsFbgAylqA7IAJWp9_N6dL5p8DHZTwlZ4IV8L1CtCALs7XVqvcQKHCCzB63Y8PgVDCAqpQSRb79JPVD4pZwkBKpOknfEY5y9wfbswZiRKdgz7o61_oFnd-yywpse-23HD6v0htThVF1SuGL1PuvGJ8p334nt9bpkZO3gaTh1xVD_uJMwHzbuBCF33_f-I5QMZO6bVooXqGfe1zvl3nDrPEjq1aPulvtP8RgREYEqE6b2hB8jouTiC_WpE3qrdMw9sfWGFbm04qC-2Zjoa1yYSXoxmYd0SnliSYHAad9aXoEmFENezQV-of7sc-NX1-2nAXRAEhaqh0IRuJwB4_sG7SvQmnanwkz-sBYxKqkoFpOsZ6hblgPDOPYY2NAsZlYkjvAL2mpiInrsmY_GzGsfwPeAx31iozImX75rao8rm-XucAmCIkRlpBz6MYKCjQgyRz3UtZCJ2DYF4lKqTjphEAgclbYZ7KiCuTn9HualwtEmVzHHFneHMKl7KnRQk-9wjgiyQ5nlsVpCCblg6JKr9of4utuPO3cBvbjhB4_ueQ40cpWVOICcOLS7_w0i3pCq1ZKDEMrYDJfz87r2sU9kw1zeFQk';

var kuksa_context = {
    authToken: TEST_TOKEN,
    socket: undefined,
    target: DEFAULT_TARGET,
}

var pathToHandler = null;

function logReceivedMessage(data) {
    console.log('Received message:', data)
}

function logConnectionStatus(status, event) {
    console.log('Connection status:', status);
}

function kuksaws_onopen(event) {
    logConnectionStatus('Connected.', event);

    authorize();
    subscribe(PATHS.volume);
}

function kuksaws_onerror(event) {
    logConnectionStatus('Failed to connect:', event);
}

function kuksaws_onmessage(event) {
    logReceivedMessage(event.data);

    var jsonData = JSON.parse(event.data);

    if (jsonData.action == 'get' ||
        jsonData.action =='subscription') {
        updateVehicleInfo(jsonData);
    }
}

function updateVehicleInfo(message) {
    var value = message.data.dp.value;
    var path = message.data.path;

    if (!pathToHandler.has(path)) {
        console.log('Handler not found for', path);
        return;
    }

    var handler = pathToHandler.get(path);
    handler.update(path, value)
}

function send(action, values) {
    var uuid = uuidv4();
    var data = Object.assign({
        action: action,
        tokens: kuksa_context.authToken,
        requestId: uuid,
    }, values);
    var message = JSON.stringify(data);
    console.log('Sent message:', message);
    kuksa_context.socket.send(message);
    return uuid;
}

function subscribe(path) {
    return send('subscribe', { path: path });
}

function authorize() {
    return send('authorize');
}

export function get(path) {
    return send('get', { path: path });
}

export function set(path, value) {
    return send('set', { path: path, value: value });
}

export function init(handlers, onopen) {
    pathToHandler = new Map(handlers);
    if (kuksa_context.socket == undefined) {
        kuksa_context.socket = new WebSocket(kuksa_context.target);
        kuksa_context.socket.onopen = function() {
            kuksaws_onopen();
            if (onopen) {
               onopen(); 
            }
        };
        kuksa_context.socket.onerror = kuksaws_onerror;
        kuksa_context.socket.onmessage = kuksaws_onmessage;
    }
}
