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

public class Lifter : MonoBehaviour
{
    [SerializeField] protected float _maxPlaceRange = 3f;
    [SerializeField] protected LayerMask _placeLayers;
    [SerializeField] protected Transform _lookPivot;
    [SerializeField] protected Transform _liftPivot;
    protected Liftable _currentLiftable;
    
    public Liftable liftingObject
    {
        get
        {
            return _currentLiftable;
        }
    }


    public bool Lift (Liftable liftable)
    {
        if (_currentLiftable != null || !liftable.Lift(this))
            return false;
        _currentLiftable = liftable;
        _currentLiftable.transform.SetParent(_liftPivot);
        _currentLiftable.transform.localPosition = Vector3.zero;
        _currentLiftable.transform.localRotation = Quaternion.identity;
        return true;
    }

    public bool Drop()
    {
        if (_currentLiftable==null)
            return false;
        _currentLiftable.transform.localPosition = Vector3.zero;
        _currentLiftable.transform.localRotation = Quaternion.identity;
        _currentLiftable.transform.SetParent(null);
        _currentLiftable.Drop(this,_lookPivot.transform.forward);
        _currentLiftable = null;
        return true;
    }

    public bool Place()
    {
        if (_currentLiftable == null)
            return false;
        RaycastHit hit;
        bool hitted = Physics.Raycast(_lookPivot.position, _lookPivot.forward, out hit, _maxPlaceRange, _placeLayers);
        if (!hitted)
            return false;

        _currentLiftable.transform.SetParent(null);
        if (_currentLiftable.Place(this, hit.point, hit.normal, _lookPivot.transform.rotation))
        {
            _currentLiftable = null;
            return true;
        }
        return false;
    }
}
