using System;
using System.Collections.Generic;

using Pingchuan.BeijingSafeguard.Model;

namespace Pingchuan.BeijingSafeguard.DAL
{
    public class TaskDAL : BaseDAL
    {
        public static void Add(Task task)
        {
            db.Insert(task);
        }

        public static List<Task> GetList(int userId, string regionCode, DateTime startTime, DateTime endTime, List<string> tags)
        {
            string sql = GetSql(userId, regionCode, startTime, endTime, tags);

            return db.Fetch<Task>(sql);
        }

        public static void Delete(string id)
        {
            db.Execute("DELETE FROM tasks WHERE id = @0", id);
        }

        public static List<Task> GetTaskIdByRegion(string region)
        {
            string sql = $@"SELECT g.task_id id FROM tags g, tasks t WHERE g.task_id = t.id AND t.region = '{region}'";

            return db.Fetch<Task>(sql);
        }

        public static string GetSql(int userId, string regionCode, DateTime startTime, DateTime endTime, List<string> tags)
        {
            if (tags != null)
            {
                string tagsString = string.Join(",", tags.ToArray());

                return $@"select c.*
                            from tasks c, tags t 
                            where c.user_id = {userId} and c.region = '{regionCode}' and c.release_time >= '{startTime}' and c.release_time < '{endTime}' and c.id = t.task_id and t.`name` in({tagsString})
                            order by c.release_time desc";
            }
            
            return $@"select c.* from tasks c 
                            where c.user_id = {userId} and c.region = '{regionCode}' and c.release_time >= '{startTime}' and c.release_time < '{endTime}' 
                            order by c.release_time desc";
        }
    }
}