//
// Copyright 2016-2021 by Garmin Ltd. or its subsidiaries.
// Subject to Garmin SDK License Agreement and Wearables
// Application Developer Agreement.
//

import Toybox.Application.Storage;
import Toybox.Lang;
import Toybox.WatchUi;

class TzCache extends WatchUi.Menu2 {

var MAX = 16;       // maximum size of the cache

var max;            // current size of the cache
var tz_name;        // cache of time zone name
var tz_index;       // cache on index into the tz info array

//! Constructor
public function initialize()
{

    max = Storage.getValue("TZmax");
    if (max != null) {
        tz_name = Storage.getValue("TZname");
        tz_index = Storage.getValue("TZindex");
        return;
    }

    reset();
}

public function get(idx)
{

    var name = tz_name[idx];
    var index = tz_index[idx];
    return [ name, index ];
}

public function index(name)
{

    for (var i = 0; i < max; ++i) {
        if (name.equals(tz_name[i])) {
            return i; }
    }
    return -1;
}

public function push(name, idx)
{

    for (var i = 0; i < max; ++i) {
        if (tz_name[i].equals(name)) {
            return; }
    }

    if (max < MAX) {
        ++max; }

    for (var i = max - 2; i >= 1; --i) {
        tz_name[i + 1] = tz_name[i];
        tz_index[i + 1] = tz_index[i];
    }
    tz_name[1] = name;
    tz_index[1] = idx;

    save();
}

public function reset()
{

    tz_name = new [MAX];
    tz_index = new [MAX];

    max = 1;
    tz_name[0] = "Local";
    tz_index[0] = 0;

    save();
}

private function save()
{

    Storage.setValue("TZmax", max);
    Storage.setValue("TZname", tz_name);
    Storage.setValue("TZindex", tz_index);
}

public function prt(len)
{

    C.logger("TZ cache:" + max);
    if (len == null)
    {
        len = max;
    } else {
        len = (len < max) ? len : max;
    }
    for (var i = 0; i < len; ++i) {
        C.logger("  " + i + ":" + tz_name[i] + ", " + tz_index[i]);
    }
}

}

