// Copyright (c) Strange Loop Games. All rights reserved.
// See LICENSE file in the project root for full license information.

namespace Eco.Mods.TechTree
{
    using Eco.Gameplay.Items;
    using Eco.Gameplay.Players;
    using Eco.Gameplay.Interactions;
    using Eco.Shared.Networking;
    using Eco.Shared.Serialization;
    using Eco.Shared.Localization;
    using System;
    using System.ComponentModel;
    using System.Linq;
    using PropertyChanged;

    /// <summary> Cameras allow users to capture and store images. </summary>
    /// <remarks> It's a 'ToolItem' because it needs durability, but it doesn't interact with any other items directly. </remarks>
    [Category("Hidden"), LocDescription("Used to capture epic moments."), AddINotifyPropertyChangedInterface]
    public partial class CameraItem : ToolItem
    {
        public override bool PreventUseWithCarriedItems  => false; //Should be allowed to capture a screenshot even when carrying items.
        public override bool ShouldHighlight(Type block) => false; //Disable highlighting other items and blocks.

        public override InteractResult OnActRight(InteractionContext context)
        {
            if (this.Durability <= 0) return InteractResult.FailureLoc($"This camera doesn't have any film.");

            //Open UI on client with this camera's view in BSON.   At the moment this makes the UI's Save Button call the 'CaptureImage' RPC.
            context.Player.OpenUI(this, "CameraModeUI", "camera");

            return InteractResult.Success;
        }

        /// <summary> Capture an image and store it on the camera's memory. </summary>
        /// <remarks> 'imageData' should be a PNG in 'byte[]' form.         </remarks>
        [RPC] public async void CaptureImage(Player player, byte[] imageData)
        {
            if (this.Durability <= 0) { player.OkBoxLocStr("This camera doesn't have any film."); return; }

            if (player.User.Inventory.ToolbarBackpack.Stacks.Any(stack => stack.Item == null))      //If player has empty slot in the backpack or toolbar                                                                  //If there are any empty stacks that can hold the picture item
            {
                var tex = await UserTextureManager.Obj.GetNewUserTexture(imageData, player.User);   //Create a new userTexture
                var pic = new PictureItem(tex);                                                     //Create the picture item with the userTexture
                player.User.Inventory.TryAddItem(pic);                                              //Add it to the inventory
                this.Durability--;                                                                  //Reduce camera film
            }
            else player.OkBoxLocStr("Not enough space in the inventory.");                          //Send to void storage instead maybe?
        }
    }
}
