﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TowerSQL {

    public class GroupByClause : ISqlClause {

        protected List<string> parts = new List<string>();

        public GroupByClause() { }

        public GroupByClause(GroupByType type) {
            this.Type = type;
        }

        public GroupByType Type {
            get;
            set;
        }

        public GroupByClause AddPart(string columnName) {
            parts.Add(columnName);

            return this;
        }

        public string Evaluate(SqlQuery query) {
            StringBuilder builder = new StringBuilder(64);

            builder.Append("GROUP BY ");

            if (this.Type != GroupByType.Default) {
                builder.Append(this.Type.ToString().ToUpper());
                builder.Append('(');
            }

            foreach (var part in this.parts) {
                builder.Append(SqlSanitizer.SanitizeObjectName(part));
                builder.Append(',');
            }

            builder[builder.Length - 1] = ' ';

            if (this.Type != GroupByType.Default) {
                builder.Append(") ");
            }

            return builder.ToString();
        }

    }

}
