using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using System.IO;
using System.Text;

using Learn_CSS.APP.Web.Models.Entities;

namespace Learn_CSS.APP.Web.Models.Services
{
    public class TaskSerializerService
    {
        readonly char SplitChar;

        public TaskSerializerService(char SplitChar) 
        {
            this.SplitChar = SplitChar;
        }

        public TaskEntity Load(string file)
        {
            TaskEntity res = new TaskEntity()
            {
                FileName = Path.GetFileName(file)
            };

            var type = typeof(TaskEntity);
            var properties = type.GetProperties()
                .Where(e => e.CanWrite)
                .ToList();

            string text;

            using (FileStream stream = new FileStream(file, FileMode.Open))
            {
                using (StreamReader reader = new StreamReader(stream))
                {
                    text = reader.ReadToEnd();
                }
            }

            var data = text.Split(SplitChar)
                .Where(e => !string
                .IsNullOrEmpty(e)).ToList();

            foreach (var elem in data)
            {
                using (StringReader reader = new StringReader(elem))
                {
                    var elem_key = reader.ReadLine().Trim();
                    var elem_text = reader.ReadToEnd().Trim();

                    var property = properties.FirstOrDefault(e => e.Name == elem_key);
                    if (property == null)
                    {
                        continue;
                    }

                    property.SetValue(res, elem_text);
                }
            }

            return res;
        }
        public void Save(TaskEntity entity, string file)
        {
            var type = typeof(TaskEntity);
            var properties = type.GetProperties()
                .Where(e => e.CanWrite)
                .ToList();


            StringBuilder text = new StringBuilder();
            foreach (var elem in properties)
            {
                text.Append(SplitChar + elem.Name + "\n" + elem.GetValue(entity) + "\n");
            }

            using (FileStream stream = new FileStream(file, FileMode.Create))
            {
                using (StreamWriter writer = new StreamWriter(stream))
                {
                    writer.Write(text.ToString());
                }
            }
        }

    }
}