<commit_before>﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Text;

using PepperSharp;

namespace FileIO
{
    public class FileIO : Instance
    {

        PPResource fileSystem;
        PPResource messageLoop;

        // Indicates whether file_system_ was opened successfully. We only read/write
        // this on the file_thread_.
        bool isFileSystemReady = false;

        public FileIO (IntPtr handle) : base(handle)
        {
            fileSystem = PPBFileSystem.Create(this, PPFileSystemType.Localpersistent);

            HandleMessage += OnHandleMessage;
            Initialize += OnInitialize;
        }

        private void OnInitialize(object sender, InitializeEventArgs args)
        {

            // Open the file system on the file_thread_. Since this is the first
            // operation we perform there, and because we do everything on the
            // file_thread_ synchronously, this ensures that the FileSystem is open
            // before any FileIO operations execute.
            messageLoop = PPBMessageLoop.Create(this);
            StartFileMessageLoop();

            PPBMessageLoop.PostWork(messageLoop, new CompletionCallback(OpenFileSystem), 0);
        }

        async void StartFileMessageLoop()
        {
            await Task.Run(() => {
                var messageLoopResult = (PPError)PPBMessageLoop.AttachToCurrentThread(messageLoop);
                if (messageLoopResult != PPError.Ok)
                    ShowErrorMessage("StartMessageLoop - AttachToCurrentThread: ", messageLoopResult);
                messageLoopResult = (PPError)PPBMessageLoop.Run(messageLoop);
                if (messageLoopResult != PPError.Ok)
                    ShowErrorMessage("StartMessageLoop - Run: ", messageLoopResult);
            });
        }



        /// <summary>
        /// Handler for messages coming in from the browser via postMessage().  The
        /// @a var_message can contain anything: a JSON string; a string that encodes
        /// method names and arguments; etc.
        ///
        /// Here we use messages to communicate with the user interface
        ///
        /// </summary>
        /// <param name="vmessage">The message posted by the browser.</param>
        private void OnHandleMessage(object sender, Var varMessage)
        {

            if (!varMessage.IsArray)
                return;

            // Message should be an array with the following elements:
            // [command, path, extra args]
            var message = new VarArray(varMessage);
            
            var command = message[0].AsString();
            var fileName = message[1].AsString();

            if (fileName.Length == 0 || fileName[0] != '/')
            {
                ShowStatusMessage("File name must begin with /");
                return;
            }

            
            Console.WriteLine($"command: {command} file_name: {fileName}");
            if (command == "load")
            {
                PPBMessageLoop.PostWork(messageLoop, new CompletionCallback<string>(Load, fileName), 0);
                
            }
            else if (command == "save")
            {
                var fileText = message[2].AsString();
                PPBMessageLoop.PostWork(messageLoop, new CompletionCallback<string, string>(Save, fileName, fileText), 0);
            }
            else if (command == "delete")
            {
                PPBMessageLoop.PostWork(messageLoop, new CompletionCallback<string>(Delete, fileName), 0);
            }
            else if (command == "list")
            {
                var dirName = fileName;
                PPBMessageLoop.PostWork(messageLoop, new CompletionCallback<string>(List, dirName), 0);
            }
            else if (command == "makedir")
            {
                var dirName = fileName;
                PPBMessageLoop.PostWork(messageLoop, new CompletionCallback<string>(MakeDir, dirName), 0);
            }
            else if (command == "rename")
            {
                var neName = message[2].AsString();
                PPBMessageLoop.PostWork(messageLoop, new CompletionCallback<string, string>(Rename, fileName, neName), 0);
            }
        }

        private void Delete(PPError result, string file_name)
        {
            if (!isFileSystemReady)
            {
                ShowErrorMessage("File system is not open", PPError.Failed);
                return;
            }

            var fileref = PPBFileRef.Create(fileSystem, file_name);

            result = (PPError)PPBFileRef.Delete(fileref, new BlockUntilComplete());
            if (result == PPError.Filenotfound)
            {
                ShowErrorMessage("File/Directory not found", result);
                return;
            }
            else if (result != PPError.Ok)
            {<commit_msg>Modify example FileIO that was using the bindings PPBMessageLoop to use the new MessageLoop class.<commit_after>﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Text;

using PepperSharp;

namespace FileIO
{
    public class FileIO : Instance
    {

        PPResource fileSystem;
        MessageLoop messageLoop;

        // Indicates whether file_system_ was opened successfully. We only read/write
        // this on the file_thread_.
        bool isFileSystemReady = false;

        public FileIO (IntPtr handle) : base(handle)
        {
            fileSystem = PPBFileSystem.Create(this, PPFileSystemType.Localpersistent);

            HandleMessage += OnHandleMessage;
            Initialize += OnInitialize;
        }

        private void OnInitialize(object sender, InitializeEventArgs args)
        {

            // Open the file system on the file_thread_. Since this is the first
            // operation we perform there, and because we do everything on the
            // file_thread_ synchronously, this ensures that the FileSystem is open
            // before any FileIO operations execute.
            messageLoop = CreateMessageLoop();
            //StartFileMessageLoop();
            var startTask = messageLoop.Start();

            messageLoop.PostWork(new CompletionCallback(OpenFileSystem));
        }

        /// <summary>
        /// Handler for messages coming in from the browser via postMessage().  The
        /// @a var_message can contain anything: a JSON string; a string that encodes
        /// method names and arguments; etc.
        ///
        /// Here we use messages to communicate with the user interface
        ///
        /// </summary>
        /// <param name="vmessage">The message posted by the browser.</param>
        private void OnHandleMessage(object sender, Var varMessage)
        {

            if (!varMessage.IsArray)
                return;

            // Message should be an array with the following elements:
            // [command, path, extra args]
            var message = new VarArray(varMessage);
            
            var command = message[0].AsString();
            var fileName = message[1].AsString();

            if (fileName.Length == 0 || fileName[0] != '/')
            {
                ShowStatusMessage("File name must begin with /");
                return;
            }

            
            Console.WriteLine($"command: {command} file_name: {fileName}");
            if (command == "load")
            {
                messageLoop.PostWork(new CompletionCallback<string>(Load, fileName));
                
            }
            else if (command == "save")
            {
                var fileText = message[2].AsString();
                messageLoop.PostWork(new CompletionCallback<string, string>(Save, fileName, fileText));
            }
            else if (command == "delete")
            {
                messageLoop.PostWork(new CompletionCallback<string>(Delete, fileName));
            }
            else if (command == "list")
            {
                var dirName = fileName;
                messageLoop.PostWork(new CompletionCallback<string>(List, dirName));
            }
            else if (command == "makedir")
            {
                var dirName = fileName;
                messageLoop.PostWork(new CompletionCallback<string>(MakeDir, dirName));
            }
            else if (command == "rename")
            {
                var neName = message[2].AsString();
                messageLoop.PostWork(new CompletionCallback<string, string>(Rename, fileName, neName));
            }
        }

        private void Delete(PPError result, string file_name)
        {
            if (!isFileSystemReady)
            {
                ShowErrorMessage("File system is not open", PPError.Failed);
                return;
            }

            var fileref = PPBFileRef.Create(fileSystem, file_name);

            result = (PPError)PPBFileRef.Delete(fileref, new BlockUntilComplete());
            if (result == PPError.Filenotfound)
            {
                ShowErrorMessage("File/Directory not found", result);
                return;
            }
            else if (result != PPError.Ok)
            {
{'fraction_non_alphanumeric': 0.09081988661142608, 'fraction_numerical': 0.0020715220235499347, 'mean_word_length': 1.735759021771548, 'pattern_counts': {'":': 0, '<': 23, '<?xml version=': 0, '>': 24, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6512896', 'n_tokens_mistral': 2238, 'n_tokens_neox': 2189, 'n_words': 615}