using UnityEngine;
using System.Collections;
using System;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;


public class DataController : MonoBehaviour {

	#region Singleton

	public static DataController instance;

	void Awake()
	{
		instance = this;

		if (instance == null) 
		{
			instance = this;
		} 
		else if (instance != this) 
		{
			Destroy (gameObject);
		}

		DontDestroyOnLoad (gameObject);
	}

	#endregion

	private PlayerData data;

    //Очистка файла сохранения
	public void Reset()
	{
		if (File.Exists (Application.persistentDataPath + "/playerInfo.dat")) 
		{
			print ("File exist, reset...");
            CreateSaveFile();
        } 
		else 
		{
			print ("File not exist, create new one...");
            CreateSaveFile();
		}
	}

    private void CreateSaveFile()
    {
        BinaryFormatter bf = new BinaryFormatter();
        FileStream file = File.Create(Application.persistentDataPath + "/playerInfo.dat");

        PlayerData data = new PlayerData();
        data.SetDefaultValues();

        bf.Serialize(file, data);
        file.Close();
    }

    //Сохранение в файл
	public void Save()
	{
		if (File.Exists (Application.persistentDataPath + "/playerInfo.dat"))
        {
            print("Save in progress...");

			BinaryFormatter bf = new BinaryFormatter ();
			FileStream file = File.Open (Application.persistentDataPath + "/playerInfo.dat", FileMode.Open);

			PlayerData data = new PlayerData ();

            //Сохранение значения выбранного языка
			if (LocalizationManager.instance == true)
            {
				data.lang = LocalizationManager.instance.defaultLang;
			}

            //Сохранение значений из меню настроек
            if (SettingsMenu.instance == true)
            {
                //Громкость музыки и звуков
                data.volumeMusic = SettingsMenu.instance.musicSlider.value;
                data.volumeSound = SettingsMenu.instance.soundSlider.value;

                //Разрешение экрана
                data.resolutionWidth = SettingsMenu.instance.resolutionWidth;
                data.resolutionHeight = SettingsMenu.instance.resolutionHeight;
                print("Saving res: " + data.resolutionWidth + "x" + data.resolutionHeight);

                //Полный экран
                data.fullscreen = Screen.fullScreen;

                //Качество
                data.quality = QualitySettings.GetQualityLevel();
            }

            if (Game.game == true)
            {
                data.money = Game.game.player.GetSavedValues(data).money;
                data.armorLevel = Game.game.player.GetSavedValues(data).armorLevel;
                data.currentHealth = Game.game.player.GetSavedValues(data).currentHealth;
                data.maxHealth = Game.game.player.GetSavedValues(data).maxHealth;
                data.currentHealthPotion = Game.game.player.GetSavedValues(data).currentHealthPotion;

                data.hasPistol = Game.game.weaponManager.GetSavedValues(data).hasPistol;
                data.hasMachineGun = Game.game.weaponManager.GetSavedValues(data).hasMachineGun;
                data.hasShotGun = Game.game.weaponManager.GetSavedValues(data).hasShotGun;
                data.hasRifle = Game.game.weaponManager.GetSavedValues(data).hasRifle;

                data.pistolLevel = Game.game.weaponManager.GetSavedValues(data).pistolLevel;
                data.machineGunLevel = Game.game.weaponManager.GetSavedValues(data).machineGunLevel;
                data.shotGunLevel = Game.game.weaponManager.GetSavedValues(data).shotGunLevel;
                data.rifleLevel = Game.game.weaponManager.GetSavedValues(data).rifleLevel;

                data.ammunition = new int[Game.game.weaponManager.GetSavedValues(data).ammunition.Length];
                for (int i = 0; i < Game.game.weaponManager.GetSavedValues(data).ammunition.Length; i++)
                {
                    data.ammunition[i] = Game.game.weaponManager.GetSavedValues(data).ammunition[i];
                }

                data.mapLengthCurrent = Game.game.map.GetSavedValues(data).mapLengthCurrent;
                data.currentMovesToTrader = Game.game.map.GetSavedValues(data).currentMovesToTrader;
                data.currentMovesToNextDifficultLvl = Game.game.map.GetSavedValues(data).currentMovesToNextDifficultLvl;
            }

            bf.Serialize (file, data);
			file.Close ();

            print("Save complete!");
		}
        else
        {
			Reset ();
		}
	}

    //Загрузка файла сохранения
	public void Load()
	{
		if (File.Exists (Application.persistentDataPath + "/playerInfo.dat")) {

            print("Load in progress...");

			BinaryFormatter bf = new BinaryFormatter ();
			FileStream file = File.Open (Application.persistentDataPath + "/playerInfo.dat", FileMode.Open);

			PlayerData data = (PlayerData)bf.Deserialize (file);

            //Загрузка значения выбранного языка
			if (LocalizationManager.instance == true)
            {
				LocalizationManager.instance.defaultLang = data.lang;
			}

            //Загрузка значений для меню настроек
            if (SettingsMenu.instance == true)
            {
                //Музыка
                SettingsMenu.instance.SetMusicSlider(data.volumeMusic);
                SettingsMenu.instance.SetMusicVolume(data.volumeMusic);

                //Звуки
                SettingsMenu.instance.SetSoundSlider(data.volumeSound);
                SettingsMenu.instance.SetSoundVolume(data.volumeSound);

                //Разрешение экрана
                SettingsMenu.instance.resolutionWidth = data.resolutionWidth;
                SettingsMenu.instance.resolutionHeight = data.resolutionHeight;
                print("Loading res: " + data.resolutionWidth.ToString() + "x" + data.resolutionHeight.ToString());

                //Полный экран
                SettingsMenu.instance.SetUpFullscreen(data.fullscreen);

                //Качество
                SettingsMenu.instance.SetQuality(data.quality);
            }

            if (Game.game == true)
            {
                Game.game.player.SetLoadedValues(data);
                Game.game.weaponManager.SetLoadedValues(data);
                Game.game.map.SetLoadedValues(data);
            }

            file.Close();

            print("Load succesfull!");
        }
		else
        {
			Reset ();
		}
	}
}
