///Licensed under Creative Commons Attribution 4.0 License, Written by Clemens Winter and Vladislav Nachev
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DocumentFormat.OpenXml.Packaging;

namespace Exploitation
{
    /// <summary>
    /// Read bat parameters from input files, e.g. "~\Exploit\Exploitation\Flower Bat World\Bats3-Selection.xlsx"
    /// Further instructions in the file.
    /// </summary>
    public class CreateBats : CreateAgents
    {
        public static Func<int, Perception, Physiology, Ressource[], Memory> memoryFactory;
        public static Func<int, Memory, Decision> decisionFactory;
        public int alternationrepeats;
        public int[] altSequence;
        public double gamma;
       
        
        string subDir, filename, agentsTable;


        public CreateBats(string subDir, string filename, string table)
        {
            this.subDir   = subDir;
            this.filename = filename;
            agentsTable = table; 
        }


        public AgentManager CreateAgents(Ressource[] ressources)
        {
           

            SpreadsheetDocument spreadsheet = SpreadsheetDocument.Open(subDir + "//" + filename, false);
            Table BatTable = spreadsheet.Table(agentsTable);

            List<Agent> agents = new List<Agent>();

            int id = 0;

                foreach (var r in BatTable.TableRows())
            {

                Physiology physiology = new BatPhysiology(int.Parse(r["stomachVol"].Value),
                                                            double.Parse(r["digestRate"].Value),
                                                            int.Parse(r["maxFeedPortion"].Value));
                Perception perception = new Perception(int.Parse(r["perceptionType"].Value), double.Parse(r["gamma"].Value),
                    double.Parse(r["Lapse"].Value), double.Parse(r["ThresholdV"].Value), double.Parse(r["SlopeV"].Value),
                    double.Parse(r["ThresholdC"].Value), double.Parse(r["SlopeC"].Value));
                Memory memory = memoryFactory(int.Parse(r["memoryType"].Value), perception, physiology, ressources);
                Personality personality = new Personality(int.Parse(r["personalityType"].Value));
                Decision decision = decisionFactory(int.Parse(r["decisionType"].Value), memory);
                alternationrepeats = int.Parse(r["nAlternations"].Value);
                altSequence = (r["altSequence"].Value).Split('-').Select(num => int.Parse(num)).ToArray();
                agents.Add(new Agent(physiology, memory, perception, personality, decision, id++, alternationrepeats, altSequence));
            }
            
            return new BatManager(agents.ToArray());
        }

    }
}