using System.Text;
using NcProgramManager;

namespace NcProgramManager.Cnc.Fanuc
{
    internal sealed class ModernFocasDialect : IFocasDialect
    {
        public FanucDialect Dialect { get { return FanucDialect.Modern; } }
        public bool SupportsPathBasedPrograms { get { return true; } }
        public bool SupportsAlmMsg2 { get { return true; } }

        public short DownloadStart(ushort hndl, string folderPath, short fileType = 0)
        {
            return Focas1.cnc_dwnstart4(hndl, fileType, folderPath);
        }

        public short DownloadData(ushort hndl, ref int len, char[] data)
        {
            return Focas1.cnc_download4(hndl, ref len, data);
        }

        public short DownloadEnd(ushort hndl)
        {
            return Focas1.cnc_dwnend4(hndl);
        }

        public short UploadStart(ushort hndl, string fileName, long programNumber, short fileType = 0)
        {
            return Focas1.cnc_upstart4(hndl, fileType, fileName);
        }

        public short UploadData(ushort hndl, ref int len, char[] data)
        {
            return Focas1.cnc_upload4(hndl, ref len, data);
        }

        public short UploadEnd(ushort hndl)
        {
            return Focas1.cnc_upend4(hndl);
        }

        public short ReadAlarmMessages(ushort hndl, ref short num, string[] outBuffer)
        {
            var arr = new Focas1.ODBALMMSG2_data_custom[outBuffer.Length];
            short ret = Focas1.cnc_rdalmmsg2_custom(hndl, -1, ref num, arr);
            for (int i = 0; i < num && i < outBuffer.Length; i++)
                outBuffer[i] = arr[i].msg_len > 0 ? arr[i].alm_msg : "";
            return ret;
        }

        public short ReadOperatorMessages(ushort hndl, ref short num, string[] outBuffer)
        {
            var arr = new Focas1.OPMSG3_data_custom[outBuffer.Length];
            short ret = Focas1.cnc_rdopmsg3_custom(hndl, 4, ref num, arr);
            for (int i = 0; i < num && i < outBuffer.Length; i++)
                outBuffer[i] = arr[i].char_num > 0 ? arr[i].data : "";
            return ret;
        }

        public string ReadMainProgramIdentifier(ushort hndl, out short ret)
        {
            byte[] buf = new byte[242];
            ret = Focas1.cnc_pdf_rdmain(hndl, buf);
            return ASCIIEncoding.ASCII.GetString(buf).TrimEnd('\0');
        }

        public short ReadActiveProgramComment(ushort hndl, byte[] buffer, out int charsRead)
        {
            uint len = (uint)buffer.Length;
            uint rows = 1;
            byte[] main = new byte[242];
            Focas1.cnc_pdf_rdmain(hndl, main);
            string mainPath = ASCIIEncoding.ASCII.GetString(main).TrimEnd('\0');
            short ret = Focas1.cnc_rdpdf_line(hndl, mainPath, 0, buffer, ref rows, ref len);
            charsRead = (int)len;
            return ret;
        }
    }
}
