using System;
using System.Collections;
using System.Collections.Generic;
using System.Security.Cryptography;
using UnityEngine;
using UnityEngine.InputSystem;

public class ArtefactPreview : MonoBehaviour
{
    [SerializeField]
    private PlayerInputSettings _inputSettings;
    
    [SerializeField]
    private PlayerInput _playerInput;
    
    private GameObject _artefactInstance;
    private Quaternion _artefactRotation = Quaternion.identity;
    
    private bool _isPressed = false;
    private bool _useVelocity = false;
    private Vector2 _velocity = Vector2.zero;

    private bool Active => gameObject.activeSelf && ( _isPressed && !_useVelocity );

    private void OnEnable()
    {
        ChangeInput( _playerInput );
    }

    public void Preview( GameObject artefact )
    {
        if ( _artefactInstance )
            Destroy( _artefactInstance );
        
        _artefactInstance = Instantiate( artefact, transform );
        _playerInput.enabled = true;
    }

    public void Dismiss()
    {
        _playerInput.enabled = false;
    }

    public void PreviewEnable( InputAction.CallbackContext context )
    {
        _isPressed = context.ReadValueAsButton();
    }
    
    public void PreviewVelocity(InputAction.CallbackContext context)
    {
        _velocity = context.ReadValue<Vector2>();
    }
    
    public void PreviewDelta(InputAction.CallbackContext context)
    {
        if ( _artefactInstance && Active )
        {
            Rotate( context.ReadValue<Vector2>() * _inputSettings.MouseSensitivity );
        }
    }

    private void Rotate( Vector2 delta )
    {
        var axes = new Vector3( delta.y, -delta.x, 0f );
        _artefactInstance.transform.Rotate( axes, Space.World );
    }

    public void ChangeInput( PlayerInput playerInput )
    {
        switch ( playerInput.currentControlScheme )
        {
            case InputSchemes.PCMR:
                _useVelocity = false;
                break;
            
            case InputSchemes.GAMEPAD:
                _useVelocity = true;
                break;
            
            default:
                _useVelocity = false;
                break;
        }
    }

    void Update()
    {
        if ( gameObject.activeSelf && _useVelocity )
        {
            Rotate( _velocity * ( Time.deltaTime * _inputSettings.JoypadSensitivity ) );
        }
    }
}
