using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class ResolutionAdjustment : MonoBehaviour {

    public bool isLoadOnly = false;
    [RangeAttribute(1.0f, 10.0f)]
    public float offsetTime = 2.0f;
    [RangeAttribute(30, 120)]
    public int measurementFrameCount = 90;

#if UNITY_ANDROID
    private static readonly string SavedRateTag = "SavedRate";

    private static readonly string DefaultScreenHalfHeightTag = "DefaultScreenHalfHeight";
    private static readonly string DefaultScreenHalfWidthTag = "DefaultScreenHalfWidth";
    
    private static bool isLoadedRate = false;

    private bool downResolution = false;

    void Start(){
        if(!LocalCacheManager.Exists(DefaultScreenHalfHeightTag)){
            LocalCacheManager.Save(DefaultScreenHalfHeightTag, Screen.height >> 1);
            LocalCacheManager.Save(DefaultScreenHalfWidthTag, Screen.width >> 1);
        }
        if(isLoadOnly) return ;
        LoadAndChangeResolution();
        if(Screen.height <= LocalCacheManager.Load<int>(DefaultScreenHalfHeightTag)) return ;
    	StartCoroutine(Measurement());
    }

    private void LoadAndChangeResolution(){
        if(!isLoadedRate && UsayaStorageManager.Exists(UsayaStorageFilename.Settings_Data, SavedRateTag)){
            float rate = UsayaStorageManager.Load<float>(UsayaStorageFilename.Settings_Data, SavedRateTag);
            ChangeResolution(rate);
            isLoadedRate = true;
        }
    }

    private IEnumerator Measurement(){
        yield return new WaitWhile(() => !UnityEngine.Rendering.SplashScreen.isFinished);

//        Debug.Log("ResolutionAdjustment Start");
        yield return new WaitForSeconds(offsetTime);
        List<float> list = new List<float>();
        for(int i = 0; i < measurementFrameCount; ++i){
            list.Add(Time.deltaTime);
            yield return null;
        }
        list.Sort((a, b) => {
            if(a > b) return 1;
            else if(a < b) return -1;
            else return 0;
        });
        float fps = 1.0f / list[list.Count / 2];
//        Debug.Log(string.Format("ResolutionAdjustment result:{0}", fps));
        if(fps < 50.0f){
            downResolution = true;
        }
    }
    
    private void ChangeResolution(float rate){
        int height = Mathf.Max((int)(Screen.height * rate), LocalCacheManager.Load<int>(DefaultScreenHalfHeightTag));
//        Debug.Log(string.Format("ResolutionAdjustment ChangeResolution {0} to {1}", Screen.height, height));
        int width = Mathf.Max((int)(Screen.width * rate), LocalCacheManager.Load<int>(DefaultScreenHalfWidthTag));
        Screen.SetResolution(width, height, false);
    }
    
    void OnDestroy(){
        if(isLoadOnly){
            LoadAndChangeResolution();
        }else if(downResolution){
            float rate = 0.8f;
            ChangeResolution(rate);
            UsayaStorageManager.Save(UsayaStorageFilename.Settings_Data, SavedRateTag, rate * UsayaStorageManager.LoadOrDefault<float>(UsayaStorageFilename.Settings_Data, SavedRateTag, 1.0f));
        }
    }
#endif
}
