using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FwUpdateApiSample
{
    public static class RetimerImageUtilities
    {
        private static readonly ushort _dbrDeviceId = 0x15F1;

        /// <summary>
        /// Reads from FW image file if the file is for Dbr 
        /// </summary>
        /// <param name="path">Path to FW image file to read from</param>
        /// <returns>Returns true when the image file is for Dbr; otherwise - returns false</returns>
        public static bool IsDbrImage(string path)
        {
            var deviceId = Utilities.RetrieveDeviceIdFromImage(path);
            return deviceId == _dbrDeviceId;
        }

        /// <summary>
        /// This function extracts the retimer address from image file
        /// </summary>
        /// <param name="path">Path to FW image file to read from</param>
        /// <returns>Retimer's address as configured in image file</returns>
        public static byte ExtractRetimerAddress(string path)
        {
            const string clcConfig = "CLC_CONFIG";
            const int smBusOffset = (12 * 4 + 1); // SmBuss address is located in DW12 - first byte in CLC_CONFIG

            using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read))
            {
                var sr = new StreamReader(fs, Encoding.UTF8);
                var imageAsString = sr.ReadToEnd();

                var clcConfigStartOffset = imageAsString.IndexOf(clcConfig);    // Get location of CLC_CONFIG string in file
                // In case CLC_CONFIG is not configured in file IndexOf return -1, therefore throw exception
                if (clcConfigStartOffset == -1)
                {
                    throw new TbtException(TbtStatus.SDK_RETIMER_NOT_FOUND, "Retimer SMBus address is not present in the image");
                }

                return Convert.ToByte(imageAsString[clcConfigStartOffset + smBusOffset]);
            }
        }
    }
}
