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

public class CharacterSpriteSorter : MonoBehaviour {

    [SerializeField] int sortingOrder = 0;

    [SerializeField] SpriteRenderer [] bodySR = new SpriteRenderer[0];
    [SerializeField] SpriteRenderer [] leftArmSR = new SpriteRenderer[0];
    [SerializeField] SpriteRenderer [] leftLegSR = new SpriteRenderer[0];
    [SerializeField] SpriteRenderer [] rightArmSR = new SpriteRenderer[0];
    [SerializeField] SpriteRenderer [] rightLegSR = new SpriteRenderer[0];

    [SerializeField] Transform character;
    [SerializeField] SpriteSorterData data;
    int offsetOrder = 0;

    private void OnValidate() {
        Resort();
    }

    int offsetOrderBuf;

    private void Update() {
        offsetOrderBuf = data.GetOrder(character.transform);

        if(offsetOrderBuf != offsetOrder) {
            offsetOrder = offsetOrderBuf;
            Resort();
        }
    }

    static int amountBuf;
    static int idBuf;

    void Resort() {

        amountBuf = bodySR.Length + leftArmSR.Length + leftLegSR.Length + rightArmSR.Length + rightLegSR.Length;
    
        idBuf = sortingOrder - (int)(amountBuf * 0.5f) + offsetOrder;
        
        Sort(leftArmSR, idBuf); idBuf += leftArmSR.Length;
        Sort(leftLegSR, idBuf); idBuf += leftLegSR.Length;
        Sort(bodySR, idBuf); idBuf += bodySR.Length;
        Sort(rightLegSR, idBuf); idBuf += rightLegSR.Length;
        Sort(rightArmSR, idBuf); idBuf += rightArmSR.Length;
    }

    void Sort(SpriteRenderer [] srArr, int id) {
        for(int i = 0; i < srArr.Length; i++) {
            if(srArr[i] != null) srArr[i].sortingOrder = id+i;
        }
    }

}
