using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;
using CGL.Graphics.XFileLib.Text;

namespace CGL.Graphics.XFileLib
{
    enum FloatMode
    {
        Single,
        Double,
    }
    
    public class XFile
    {
        Dictionary<string, Dictionary<string, dynamic>> data = new Dictionary<string, Dictionary<string, dynamic>>();
        /// <summary>
        /// XFile中のデータ
        /// </summary>
        public Dictionary<string, Dictionary<string, dynamic>> FileData { get { return data; } }

        public static XFile FromFile(string filename)
        {
            filename = Path.GetFullPath(filename);

            if (!File.Exists(filename))
                throw new FileNotFoundException("ファイルがみつかりません", filename);
            string fileMode = "";
            FloatMode floatMode;
            using (BinaryReader br = new BinaryReader(File.Open(filename, FileMode.Open)))
            {
                string magic = (new string(br.ReadChars(4))).Trim();
                if (magic != "xof")
                    throw new FileLoadException("XFileではありません", filename);
                br.ReadBytes(4);//バージョン読み飛ばし
                fileMode = (new string(br.ReadChars(4))).Trim();
                string f = (new string(br.ReadChars(4))).Trim();
                switch (f)
                {
                    case "0032":
                        floatMode = FloatMode.Single;
                        break;
                    case "0064":
                        floatMode = FloatMode.Double;
                        break;
                    default:
                        throw new FileLoadException("不明な浮動小数点型です:" + f, filename);
                }
                br.Close();
            }
            switch (fileMode)
            {
                case "txt":
                    {
                        string data = File.ReadAllText(filename, Encoding.GetEncoding("Shift_JIS"));
                        return XFileTextReader.FromTxtFile(data, floatMode);
                    }
                case "bin":
                    throw new NotImplementedException("バイナリ形式のXFileは読み込めません");
                case "tzip":
                    throw new NotImplementedException("zip圧縮形式のXFileは読み込めません");
                case "bzip":
                    throw new NotImplementedException("zip圧縮形式のXFileは読み込めません");
                default:
                    throw new FileLoadException("不明なXFileデータ型です");
            }
        }
        
    }
}
