using NcProgramManager;

namespace NcProgramManager.Cnc.Fanuc
{
    internal sealed class LegacyFocasDialect : IFocasDialect
    {
        public FanucDialect Dialect { get { return FanucDialect.Legacy; } }
        public bool SupportsPathBasedPrograms { get { return false; } }
        public bool SupportsAlmMsg2 { get { return false; } }

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

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

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

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

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

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

        public short ReadAlarmMessages(ushort hndl, ref short num, string[] outBuffer)
        {
            var arr = new Focas1.ODBALMMSG_data_custom[outBuffer.Length];
            short ret = Focas1.cnc_rdalmmsg_custom(hndl, 0, 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)
        {
            var prog = new Focas1.ODBPRO();
            ret = Focas1.cnc_rdprgnum(hndl, prog);
            return "O" + prog.mdata.ToString();
        }

        public short ReadActiveProgramComment(ushort hndl, byte[] buffer, out int charsRead)
        {
            ushort len = (ushort)buffer.Length;
            short blk;
            short ret = Focas1.cnc_rdexecprog(hndl, ref len, out blk, buffer);
            charsRead = len;
            return ret;
        }
    }
}
