using System;
using System.Xml;
using System.Collections.Generic;

namespace Orienteering.Competition {
    public class Runner {
        internal Orienteering.Data.Runner data;

        public Runner(Club club) {
            this.data = new Orienteering.Data.Runner();
            Club = club;
        }
        public Runner(Orienteering.Data.Runner data) {
            this.data = data;
        }

        public Runner(XmlNode xml, Club club, DataBase dataBase) {
            data = new Orienteering.Data.Runner();
            Club = club;
            foreach (XmlAttribute xmlattr in xml.Attributes) {
                if (xmlattr.Name == "name")
                    Name = xmlattr.Value;
                if (xmlattr.Name == "regNumber")
                    RegNumber = Convert.ToInt32(xmlattr.Value);
            }
            this.Save(dataBase);

            foreach (XmlNode node in xml.ChildNodes)
                if (node.Name == "result")
                    new Result(node, this, dataBase);

        }

        public string Name {
            get { return data.Name; }
            set { data.Name = value; }
        }

        public int RegNumber {
            get { return data.RegNumber; }
            set { data.RegNumber = value; }
        }

        public Club Club {
            get { return new Club(data.Club); }
            set { data.Club = value.data; }
        }

        public void Save(DataBase dataBase) {
            data.Save(dataBase.data);
        }

        public List<Result> Results(DataBase dataBase) {
            List<Result> res = new List<Result>();
            foreach (Orienteering.Data.Result result in data.Results(dataBase.data))
                res.Add(new Result(result));
            return res;
        }

        public Result Result(Stage stage, DataBase dataBase) {
            return new Result(data.Result(stage.data, dataBase.data));
        }

        public XmlNode Xml(XmlDocument xml, DataBase dataBase) {
            XmlNode res = xml.CreateNode("element", "runner", "");

            XmlAttribute nameAttr = (XmlAttribute)xml.CreateNode("attribute", "name", "");
            nameAttr.Value = Name;
            res.Attributes.Append(nameAttr);

            XmlAttribute regNumberAttr = (XmlAttribute)xml.CreateNode("attribute", "regNumber", "");
            regNumberAttr.Value = RegNumber.ToString();
            res.Attributes.Append(regNumberAttr);

            foreach (Result result in Results(dataBase))
                res.AppendChild(result.Xml(xml));

            return res;
        }
    }
}
