﻿using System.Collections.Generic;
using System.Linq;

namespace RS.JSProxyGenerator
{
    public class TemplateCreator
    {
        //reads template file and creates a new string that can be saved
        string file;
        public string newProxy { get; }

        public TemplateCreator(List<EndPointClass> endpoints)
        {
            //read file
            if (TemplateHolder.Template == null)
                TemplateHolder.ReadTemplateFile();
            file = TemplateHolder.Template;

            newProxy = GenerateProxy(endpoints);
        }

        string GenerateProxy(List<EndPointClass> endpoints)
        {
            string result = file;

            string endPointsString = string.Empty;

            foreach (var endpoint in endpoints)
            {
                endPointsString += endpoint.Name + ": self.BaseUrl + '/" + endpoint.Name + "/'";
                if (endpoint != endpoints.Last())
                    endPointsString += ",";

                endPointsString += "\n";
            }

            result = result.Replace("[ENDPOINTS]", endPointsString);

            string endPointsDefinition = string.Empty;

            foreach (var endpoint in endpoints) // go through all the endpoints
            {
                endPointsDefinition += "this." + endpoint.Name + " = {\n";

                foreach (var action in endpoint.WebActions) //go through all the actions
                {
                    endPointsDefinition += action.Name + ": function(";
                    if (action.Parameters.Count > 0)
                        foreach (var param in action.Parameters)
                        {
                            endPointsDefinition += param.Name + ", ";
                        }

                    endPointsDefinition += "callback) {\nvar data = {\n";

                    if (action.Parameters.Count > 0)
                        foreach (var param in action.Parameters)
                        {
                            endPointsDefinition += param.Name + ": " + param.Name;
                            if (param != action.Parameters.Last())
                                endPointsDefinition += ",\n";
                        }
                    endPointsDefinition += "\n};\n";

                    endPointsDefinition += "RS.Remote.call(endpoints." + endpoint.Name + "+'" + action.Name + "', data, callback, '" + action.WebMethod + "');";
                    endPointsDefinition += "\n}";
                    if (action != endpoint.WebActions.Last())
                        endPointsDefinition += ",";
                    endPointsDefinition += "\n";
                }
                endPointsDefinition += "};\n\n";
            }

            result = result.Replace("[ENDPOINTS_DEFINITIONS]", endPointsDefinition);

            return result;
        }
    }
}