using UnityEngine;

public class Quest : MonoBehaviour
{
    public bool hasStarted = false;
    public bool hasCompleted = false;

    public DialogueLine[] askText; // ask the player to complete the task
    public DialogueLine[] duringText; // what to say to the player when the task is complete
    public DialogueLine[] completionText; // what to say to the player upon completion

    public int questID = 0; // connects the quest to the registry, which gives us conditions

    public void Start()
    {
        // check if we've completed the quest
        hasCompleted = QuestRegistry.Instance.CompletedQuests.Contains(questID);
        hasStarted = QuestRegistry.Instance.ActiveQuests.Contains(questID);

        // this shouldn't be possible, but if the save is changed manually it could happen
        if (hasStarted && hasCompleted)
        {
            hasStarted = false;

            // make sure only one reference exists
            QuestRegistry.Instance.CompletedQuests.RemoveAll(id => id == questID);
            QuestRegistry.Instance.CompletedQuests.Add(questID);

            QuestRegistry.Instance.ActiveQuests.RemoveAll(id => id == questID);
            SaveSystem.Save();
        }
    }

    public void StartQuest()
    {
        hasStarted = true;
        QuestRegistry.Instance.ActiveQuests.Add(questID);
        SaveSystem.Save();
    }

    public bool CheckComplete()
    {
        QuestBool[] conditionList = QuestRegistry.Instance.QuestBoolMap[questID];

        if (conditionList != null)
        {
            foreach (QuestBool condition in conditionList)
            {
                // try each condition until we hit a false
                if (!condition.getValue())
                    return false;
            }

            // otherwise return true and mark quest complete
            QuestRegistry.Instance.ActiveQuests.Remove(questID);
            QuestRegistry.Instance.CompletedQuests.Add(questID);

            SaveSystem.Save();
            hasCompleted = true;
            return true;
        }

        return false;
    }
}
