using UnityEngine;
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json;
/// <summary>
/// 用于对项目所用到的数据进行管理
/// </summary>
public class MainMenuModel : MonoBehaviour
{
    //依据设计书输入数值
    readonly private float DefaultBaseSpeed = 25;
    readonly private float DefaultTrackLength = 125;
    readonly private float DefaultNoteStream = 5f;
    readonly private float DefaultBPM = 128;
    readonly private float DefaultBaseBPM = 128;
    /// <summary>
    /// 存储所有拍线的时间,在加载BPM组的时候就需要初始化完成
    /// </summary>
    public List<float> BPMLineTime { set; get; } = new List<float>();
    /// <summary>
    /// 当前被渲染出来的拍线数据,用于切换选择拍线
    /// </summary>
    public List<float> currentBPMLine { set; get; } = new List<float>();
    /// <summary>
    /// 当前谱面文件的主要时间组,决定拍线的渲染方式,永远取序号为0的时间组
    /// </summary>
    public BPMGroup MainBPMGroup 
    { 
        get
        { 
            return BPMGroupManager.QueryBPMGroup(0);
        }
    }
    public Chart PersistentChartData { set; get; }
    public BPMGroupModel BPMGroupManager { set; get; }
    public ChartRuntimeModel ChartRuntimeDataManager { set; get; }
    public AudioSource Song { set; get; }
    public float SongCurrentTime
    {
        get
        {
            if (Song.clip == null) return 0;
            return (float)Song.timeSamples / Song.clip.frequency;
        }
        set
        {
            Song.time = value;
        }
    }

    private void Awake()
    {
        Song = gameObject.GetComponent<AudioSource>();
        InitMainMenuModel();
    }
    private void InitMainMenuModel()
    {
        //启用BPM管理类
        BPMGroupManager = new BPMGroupModel(
            DefaultNoteStream,
            DefaultBaseSpeed,
            DefaultBaseBPM,
            DefaultTrackLength
            );

        //创建用于管理运行时逻辑的数据对象
        ChartRuntimeDataManager = new ChartRuntimeModel();
        //创建用于转换为Json对象的持久化数据对象
        PersistentChartData = new Chart();
        //初始化新项目的结构
        NewProjectData();
    }
    /// <summary>
    /// 依据时间更新所有BPM组的状态,将这个方法注册在控制层的时间变化事件中
    /// </summary>
    public void UpdateBPMGroup(float currentTime)
    {
        BPMGroupManager.UpdateBPMGroup(currentTime);
    }
    /// <summary>
    /// 向管理器申请创建新的数据项,返回创建结果
    /// </summary>
    public bool CreateBPMDataItem(int groupNum, float startTime, float currentBPM)
    {
        BPMGroupManager.CreateNewBPMGroup(groupNum, startTime, currentBPM);
        return BPMGroupManager.QueryBPMGroupDataItem(groupNum, startTime, currentBPM);
    }
    /// <summary>
    /// 向管理器申请删除指定的数据项,返回删除结果
    /// </summary>
    public bool DeleteBPMDataItem(int groupNum, float startTime, float currentBPM)
    {
        BPMGroupManager.DeleteBPMGroup(groupNum, startTime);
        return !BPMGroupManager.QueryBPMGroupDataItem(groupNum, startTime, currentBPM);
    }
    /// <summary>
    /// 这里会返回一个包含当前所有BPM数据项的集合用于让C层持有数据库的备份,之后只能通过开发的接口更改数据,C层本身并不能直接访问BPM管理器
    /// </summary>
    public List<(int GroupNum, float startTime, float currentBPM)> GetAllBPMDataItem()
    {
        return BPMGroupManager.GetAllBPMDataItem();
    }
    /// <summary>
    /// 更新所有的玩家设置
    /// </summary>
    public void UpdatePlayerSetting(float noteStream, float baseSpeed, float baseBPM, float trackLength)
    {
        BPMGroupManager.UpdatePlayerSetting(noteStream, baseSpeed, baseBPM, trackLength);

        PersistentChartData.globalConfig.baseBPM = baseBPM;
        PersistentChartData.globalConfig.baseSpeed = baseSpeed;
        PersistentChartData.globalConfig.trackLength = trackLength;
        PersistentChartData.globalConfig.noteStream = noteStream;
    }
    /// <summary>
    /// 删除指定的数据项,返回删除的情况
    /// </summary>
    public bool DeleteNoteDataItem(RuntimeBaseNoteData obj)
    {
        ChartRuntimeDataManager.DeleteDataItem(obj);

        if (ChartRuntimeDataManager.GetDataItem(obj) == null)
        {
            return true;
        }
        return false;
    }
    public RuntimeNoteData CreateNewNoteDataItem(float targetTime, float xPos, float yPos, int num)
    {
        var go = BPMGroupManager.QueryBPMGroup(num);
        if (go == null) return null;

        var item = new RuntimeNoteData(targetTime, xPos, yPos, go);
        ChartRuntimeDataManager.AddDataItem(item);
        return item;
    }
    public RuntimeDragData CreateNewDragDataItem(float targetTime, float xPos, float yPos, int num)
    {
        var go = BPMGroupManager.QueryBPMGroup(num);
        if (go == null) return null;

        var item = new RuntimeDragData(targetTime, xPos, yPos, go);
        ChartRuntimeDataManager.AddDataItem(item);
        return item;
    }
    public RuntimeFlickData CreateNewFlickDataItem(float targetTime, float xPos, float yPos, int num, FlickDirection direction)
    {
        var go = BPMGroupManager.QueryBPMGroup(num);
        if (go == null) return null;

        var item = new RuntimeFlickData(targetTime, xPos, yPos, direction, go);
        ChartRuntimeDataManager.AddDataItem(item);
        return item;
    }
    public RuntimeSnakeData CreateNewSnakeDataItem(float targetTime, float xPos, float yPos, float endXPos, float endYPos, float endTime, int num, ReferencePointLocation referencePoint)
    {
        var go = BPMGroupManager.QueryBPMGroup(num);
        if (go == null) return null;

        var item = new RuntimeSnakeData(targetTime, xPos, yPos, endXPos, endYPos, endTime, referencePoint, go);
        ChartRuntimeDataManager.AddDataItem(item);
        return item;
    }
    /// <summary>
    /// 导出运行时模型与BPM管理模型中的数据项至持久化数据结构中
    /// </summary>
    public void UpdateChartData()
    {
        ChartRuntimeDataManager.GetChartData(PersistentChartData);

        //导出BPM数据
        var bpmList = BPMGroupManager.GetDataObject();
        PersistentChartData.BPMList = bpmList;

    }
    private void NewProjectData()
    {
        //创建默认BPM组,编号为零
        BPMGroupManager.CreateNewBPMGroup(0, 0, DefaultBPM);

        InitDefaultGlobalConfig();
        InitDefaultMETAData();
    }
    /// <summary>
    /// 以默认值配置新谱面文件的全局变量
    /// </summary>
    private void InitDefaultGlobalConfig()
    {
        PersistentChartData.globalConfig.baseBPM = DefaultBaseBPM;
        PersistentChartData.globalConfig.baseSpeed = DefaultBaseSpeed;
        PersistentChartData.globalConfig.trackLength = DefaultTrackLength;
        PersistentChartData.globalConfig.noteStream = DefaultNoteStream;
        PersistentChartData.globalConfig.BPM = DefaultBPM;
    }
    /// <summary>
    /// 这里是一些测试的META数据
    /// </summary>
    private void InitDefaultMETAData()
    {
        PersistentChartData.version = "测试版本";
        //初始化谱面测试数据
        PersistentChartData.META.songName = "MusCus";
        PersistentChartData.META.songWriter = "NPVASTAR-T";
        PersistentChartData.META.chartDesigner = "Program Team";
        PersistentChartData.META.illustrator = "天辞ちゃん～BananApple～";
    }
    /// <summary>
    /// 依据路径读取Chart文件,注意,读取新的文件将会覆盖当前工程
    /// </summary>
    public void ReadChartByPath(string path)
    {
        string json = File.ReadAllText(path);
        PersistentChartData = JsonConvert.DeserializeObject<Chart>(json);
    }
    /// <summary>
    /// 将谱面文件序列化json字符串
    /// </summary>
    public string GetChartJson()
    {
        //导出前再整理一遍所有运行时数据
        UpdateChartData();
        string jsonString = JsonConvert.SerializeObject(PersistentChartData, Formatting.Indented);
        print(jsonString);
        return jsonString;
    }
}