
using System;
using System.Collections.Generic;
using System.IO;
using Unity.Ugc;
using Unity.Ugc.Common;
using Unity.Ugc.Model;
using UnityEngine;
using Unity.Ugc.File;
using UnityEditor;
using UnityEngine.UIElements;
using Image = UnityEngine.UI.Image;

namespace Unity.Ugc.Samples
{
    public class UgcSample : MonoBehaviour
    {
        private string _modId = "";
        private string _coverUrl = "";
        private byte[] _data;
        
        private string _playerId;
        private string _playerToken;

        private async void Start()
        {
            try
            {
                _playerId = "demo";
                _playerToken = "demo";
                UgcSDK.Init();
                await UgcSDK.Login(IdProvider.Hykb, "app", _playerId, _playerToken);
            }
            catch (UgcException e)
            {
                Debug.Log($"Ugc Exception code {e.Code} - {e.ErrorMessage}");
            }
            catch (Exception e)
            {
                Debug.Log($"Other Exception msg {e.Message}");
            }
        }

        public void SelectPicture()
        {
            string filepath = EditorUtility.OpenFilePanel("Select Cover","","png,jpg");
            Debug.Log(filepath);
            
            if (string.IsNullOrEmpty(filepath))
            {
                Debug.Log("no picture selected");
                return;
            }
            
            using (FileStream fs = new FileStream(filepath, FileMode.Open))
            {
                _data = new byte[fs.Length];
                var l = fs.Read(_data);
            }
        }

        private async void Update()
        {
            try
            {
                // 测试时，步骤 1 - 5 请按顺序执行
                if (Input.GetKeyDown(KeyCode.Alpha1))
                {
                    Debug.Log("Create Mod");
                    var req = new CreateModRequest()
                    {
                        Name = "Demo",
                        Author = "U",
                        Description = "Demo"
                    };
                    
                    var mod = await UgcSDK.CreateMod(req);
                    _modId = mod.Id;
                    Debug.Log($"create mod {mod.Stash.Name} successfully");
                }
                
                if (Input.GetKeyDown(KeyCode.Alpha2))
                {
                    Debug.Log("Upload Cover");
                    
                    SelectPicture();
                    if (_data != null)
                    {
                        LocalFile file = new LocalFile("cover.jpg", _data);
                        _coverUrl = await UgcSDK.UploadResource(_modId, file);
                        Debug.Log("upload cover successfully");
                    }
                }
                
                if (Input.GetKeyDown(KeyCode.Alpha3))
                {
                    Debug.Log("Update Mod");
                    var req = new UpdateModRequest()
                    {
                        Name = "Demo",
                        Author = "U",
                        Description = "Demo",
                        Cover = _coverUrl,
                        Gallery = new List<string>() { _coverUrl },
                        Properties = new Dictionary<string, string>() { { "Map", "Sea" }, { "Mode", "Online" } }
                    };
                    
                    var mod = await UgcSDK.UpdateMod(_modId, req);
                    Debug.Log($"update mod {mod.Stash.Name} successfully");
                }
                
                if (Input.GetKeyDown(KeyCode.Alpha4))
                {
                    Debug.Log("Upload Mod Files");
                    LocalFile file = new LocalFile("demo.bundle", _data);
                    var failed = await UgcSDK.UploadMod(_modId, file);
                    if (failed.Count > 0)
                    {
                        Debug.Log($"fail to upload {failed.Count} file");
                    }
                    else
                    {
                        Debug.Log("upload mod files successfully");
                    }
                }
                
                if (Input.GetKeyDown(KeyCode.Alpha5))
                {
                    Debug.Log("Submit Version");

                    var req = new SubmitVersionRequest()
                    {
                        Version = "1.0.0",
                        VersionDesc = "First Version"
                    };

                    var mod = await UgcSDK.SubmitVersion(_modId, req);
                    Debug.Log($"submit version {mod.Stash.Version}");
                }
                
                if (Input.GetKeyDown(KeyCode.Alpha6))
                {
                    Debug.Log("Show Entries");
                    
                    var entries = await UgcSDK.ListEntries(_modId);
                    Debug.Log($"total {entries.Pagination.Total} entries");
                    foreach (var entry in entries.Items)
                    {
                        Debug.Log(entry.Path);
                    }
                }
                
                if (Input.GetKeyDown(KeyCode.Alpha7))
                {
                    Debug.Log("List Published Mods");
                    var mods = await UgcSDK.ListPublishedMods(1, 100);
                    Debug.Log($"total {mods.Pagination.Total} published mods");
                    foreach (var mod in mods.Items)
                    {
                        Debug.Log(mod.Name);
                    }
                }
                
                if (Input.GetKeyDown(KeyCode.Alpha8))
                {
                    Debug.Log("List Owned Mods");
                    var mods = await UgcSDK.ListOwnedMods(1, 100);
                    Debug.Log($"total {mods.Pagination.Total} mods uploaded by current player");
                    foreach (var mod in mods.Items)
                    {
                        Debug.Log(mod.Stash.Name);
                    }
                }
                
                if (Input.GetKeyDown(KeyCode.Alpha9))
                {
                    Debug.Log("Search Mod");
                    var req = new SearchModRequest()
                    {
                        SortKey = SortKey.SubscriptionCount,
                        SortOrder = SortOrder.Desc,
                        Properties = new Dictionary<string, string>() { { "Map", "Sea" } }
                    };

                    var mods = await UgcSDK.SearchPublishedMods(req);
                    Debug.Log($"total {mods.Pagination.Total} mods matching requirements");
                    foreach (var mod in mods.Items)
                    {
                        Debug.Log(mod.Name);
                    }
                }
            }
            catch (UgcException e)
            {
                Debug.Log($"Ugc Exception code {e.Code} - {e.ErrorMessage}");
            }
            catch (Exception e)
            {
                Debug.Log($"Other Exception msg {e.Message}");
            }
        }
    }
}