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

namespace FANUC
{
    public class Fanuc : Focas1
    {
        public static ushort h;

        private static short getdtailerr(ushort handle, Fanuc.ODBERR odberr)
        {
            return Fanuc.cnc_getdtailerr(handle, odberr);
        }
    

        private static short upstart(ushort handle, short type, int startno, int endno)
        {
            return cnc_upstart3(handle, type, startno, endno);
        }

        private static short uplod(ushort handle, int length, char[] databuf)
        {
            return cnc_upload3(handle, ref length, databuf);
        }

        private static short upend(ushort handle)
        {
            return cnc_upend3(handle);
        }
        public static short upload(ushort handle, short type, int no, ref string data, Fanuc.ODBERR odberr)
        {
            int startno = no; int endno = no;
            int length = 256; char[] databuf = new char[256];
            short ret = upstart(handle, type, startno, endno);
            if (ret == Fanuc.EW_OK)
            {
                string temp = "";
                while (true)
                {
            
                    ret = uplod(handle, length, databuf);
                    temp = new string(databuf);
                    int one = temp.Length;
                    if (ret == (short)Fanuc.focas_ret.EW_BUFFER)
                    {
                        continue;
                    }
                    if (ret == Fanuc.EW_OK)
                    {
                        temp = temp.Replace("\0", "");
                        data += temp;
                        string lastchar = temp.Substring(temp.Length - 1, 1);
                        if (lastchar == "%")
                        {
                            break;
                        }
                    }
                    else
                    {
                   
                        if (odberr != null)
                        {
                            getdtailerr(handle, odberr);
                        }
                  
                        break;
                    }
                }
          
                if (ret == 0)
                {
                    ret = upend(handle);

                    return ret;
                }
                else
                {
                    upend(handle);
   
                    return ret;
                }
            }
            else
            {
     
                upend(handle);
                return ret;
            }
        }
     



    }
}
