using System.IO;
using System.Runtime.Serialization;
using Microsoft.Xna.Framework.Audio;
using Newtonsoft.Json;

namespace TouchyTickets;

[DataContract]
public class Options {

    public static Options Instance { get; private set; }

    [DataMember]
    public int RainingTicketLimit = 300;
    [DataMember]
    public float SoundVolume {
        get => this.soundVolume;
        set {
            this.soundVolume = value;
            SoundEffect.MasterVolume = value;
        }
    }
    private float soundVolume = 1;
    [DataMember]
    public bool WhileYouWereAwayMessage = true;
    [DataMember]
    public bool KeepScreenOn {
        get => this.keepScreenOn;
        set {
            this.keepScreenOn = value;
            GameImpl.Instance.Platform.SetKeepScreenOn(value);
        }
    }
    private bool keepScreenOn;
    [DataMember]
    public bool AutoBuyEnabled = true;
    [DataMember]
    public int MinTicketsForAutoBuy = 50000;

    public static void Save() {
        var file = Options.GetOptionsFile(true);
        using var stream = new JsonTextWriter(file.CreateText());
        SaveHandler.Serializer.Serialize(stream, Options.Instance);
    }

    public static void Load() {
        var file = Options.GetOptionsFile(false);
        if (file.Exists) {
            using var stream = new JsonTextReader(file.OpenText());
            Options.Instance = SaveHandler.Serializer.Deserialize<Options>(stream);
        } else {
            Options.Instance = new Options();
        }
    }

    private static FileInfo GetOptionsFile(bool create) {
        return new FileInfo(Path.Combine(SaveHandler.GetGameDirectory(create).FullName, "Options"));
    }

}