﻿using System.Collections.Generic;
using UnityEngine;

namespace JLGames.RocketDriver.Actions.Localx
{
    public static class LocalVersion
    {
        private static string m_VersionValue;

        //------------------------------

        public static bool HasVersionValue => PlayerPrefs.HasKey(LocalKeys.VersionKey);

        public static string VersionValue
        {
            get
            {
                if (null == m_VersionValue)
                {
                    m_VersionValue = PlayerPrefs.GetString(LocalKeys.VersionKey);
                }

                return m_VersionValue;
            }
        }

        public static void SetVersionValue(string value)
        {
            m_VersionValue = value;
            PlayerPrefs.SetString(LocalKeys.VersionKey, value);
            var list = VersionList;
            if (null == list)
            {
                PlayerPrefs.SetString(LocalKeys.VersionListKey, m_VersionValue);
            }
            else
            {
                var l = new List<string>();
                l.AddRange(list);
                var index = l.IndexOf(m_VersionValue);
                if (0 == index) return;
                if (-1 != index)
                {
                    l.RemoveAt(index);
                }

                l.Insert(0, m_VersionValue);
                var str = string.Join(",", l.ToArray());
                PlayerPrefs.SetString(LocalKeys.VersionListKey, str);
            }
        }

        public static string[] VersionList
        {
            get
            {
                if (!PlayerPrefs.HasKey(LocalKeys.VersionListKey))
                {
                    return null;
                }

                var str = PlayerPrefs.GetString(LocalKeys.VersionListKey);
                return string.IsNullOrEmpty(str) ? null : str.Split(',');
            }
        }
    }
}