using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using HQFPSWeapons;
using UnityEngine.Rendering.PostProcessing;

public class weaponAttachmentsMgr : MonoBehaviour
{
    public Player player;
    [SerializeField]
    public AttachmentConfig[] attachmentConfigs;
    public PostProcessVolume pp;

    DepthOfField depthOfField;
    bool aimValue;
    [Range(0.00f,1.00f)]
    public float aimed;

    bool gotScope= false;
    void Start()
    {
        player.EquippedItem.AddChangeListener((SaveableItem item) => { changeAttachments((item == null) ? "" : item.Name); });
        pp.profile.TryGetSettings(out depthOfField);
    }

    // Update is called once per frame
    void Update()
    {
        if(aimValue && aimed < 1){
            aimed+=0.05f;if(gotScope){depthOfField.focusDistance.value = 0.1f + (0.1f * (1-aimed));}
        }else if(!aimValue && aimed > 0){
            aimed-=0.05f;depthOfField.focusDistance.value =0.1f + (0.1f * (1-aimed));
        }
    }

    void changeAttachments(string item){
        StartCoroutine(waitAndChangeAttachments(item));
    }

    IEnumerator waitAndChangeAttachments(string item){
        yield return new WaitForSeconds(0.6f);
        foreach(AttachmentConfig config in attachmentConfigs){
            bool isSelected = config.weaponName == item;
            foreach(GameObject attachment in config.attachments){
                attachment.SetActive(isSelected);
                if(isSelected)gotScope = attachment.GetComponent<scopeBehaviour>()!=null;
            }
        }
    }

    public void focus(bool value){
        aimValue = value;
    }

    // IEnumerator _focus(bool value){
    //     aimed = (value) ? 0: 1;
    //     if(value){
    //         while(aimed < 1){
    //             aimed +=0.1f;
                
    //             yield return new WaitForEndOfFrame();
    //         }
    //     }else{
    //         while(aimed > 0){
    //             aimed -=0.1f;
    //             depthOfField.focusDistance.value = 1-aimed;
    //             yield return new WaitForEndOfFrame();
    //         }
    //     }
    // }
}

[Serializable]
public class AttachmentConfig{

    public string weaponName;
    public List<GameObject> attachments;
    public AttachmentConfig(string _weaponName){
        weaponName = _weaponName;
        attachments = new List<GameObject>();
    }
}