using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Serialization;

namespace ParticulateSensorRecords
{
    class XMLFileReader : IFileReader
    {
        public Location ReadDataFromFile(ConfigRecord configRecord)
        {
            // Open the file to read from on the local file system.
            // If this file is missing then return immediately from this method.

            if (!File.Exists(configRecord.Filename))
            {
                // Cannot open the file as it does not exist for whatever reason, so return immediately.
                return null;
            }

            // Open file and load into memory as XML
            XDocument xmlDoc = XDocument.Load(configRecord.Filename);
            

            // Create location (should only be one in file but retrieve first to be sure)
            var loc = (from c in xmlDoc.Descendants("Location")
                            select c).First();
           

            // Create and return a location based on report name and measures

            Location location = new Location(loc.Attribute("name").Value);

            // Obtain AirData from this location
            var airdata = from a in loc.Descendants("Reading")
                       select a;

            foreach (var c in airdata)
            {
                var date = Convert.ToDateTime(c.Attribute("date").Value);
                var particulate = Int32.Parse(c.Element("value").Value);
                var temperature = Convert.ToDouble(c.Element("temperature").Value);
                var humidity = Convert.ToDouble(c.Element("humidity").Value);

                AirData ad = new AirData(date, particulate, temperature, humidity);
                location.AirDatas.Add(ad);
            }

            return location;
        }

    }
}
