using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Util;
using Android.Views;
using Android.Widget;
using Java.IO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace GetEJDocuments_DevGr_A
{
    public class RecEJContentDialog : Dialog
    {
        public delegate string ExecuteReceiptEJTextEventHandler(int position);
        public event ExecuteReceiptEJTextEventHandler OnExecuteReceiptEJText;

        public int lstPosition {
            get
            {
                return pos;
            }
            set
            {
                pos = value;
            }
        }
        int pos;
        public RecEJContentDialog(Activity activity) : base(activity)
        {

        }
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            RequestWindowFeature((int)WindowFeatures.NoTitle);
            SetContentView(Resource.Layout.ReceiptContentDialog);
            
            TextView txtRecContent = (TextView)FindViewById(Resource.Id.txtReceipts);
            txtRecContent.Text = OnExecuteReceiptEJText(lstPosition);
            Button saveText = (Button)FindViewById(Resource.Id.btnSaveRecText);
           
            saveText.Click += (e, a) =>
            {
                VerifyStoragePermissions(MainActivity.GetInstance());
                if (WriteToFile(txtRecContent.Text, (lstPosition + 1).ToString(), MainActivity.GetInstance()))
                    MainActivity.ShowMessage("Successfully saved!", "Message");
                Dismiss();


            };
            Button cancelDialog = (Button)FindViewById(Resource.Id.btnCancelDialog);
            cancelDialog.Click += (e, a) =>
              {
                  Dismiss();
              };
        }

        private static int REQUEST_EXTERNAL_STORAGE = 1;
        private static String[] PERMISSIONS_STORAGE = {
        Android.Manifest.Permission.ReadExternalStorage,
        Android.Manifest.Permission.WriteExternalStorage};

        /**
         * Checks if the app has permission to write to device storage
         *
         * If the app does not has permission then the user will be prompted to grant permissions
         *
         * @param activity
         */
        public static void VerifyStoragePermissions(Activity activity)
        {
            // Check if we have write permission
            var permission = Android.Support.V4.App.ActivityCompat.CheckSelfPermission(activity, Android.Manifest.Permission.WriteExternalStorage);

                // We don't have permission so prompt the user
                Android.Support.V4.App.ActivityCompat.RequestPermissions(
                        activity,
                        PERMISSIONS_STORAGE,
                        REQUEST_EXTERNAL_STORAGE
                );

        }

        private bool WriteToFile(String data,string fileName, Context context)
        {
           
            try
            {
                File createDirectory = new File(Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads).AbsolutePath + "/Receipts/");

                createDirectory.Mkdirs();  // Creates directory
                File receiptFile = new File(createDirectory,fileName + ".txt");

                if (!receiptFile.Exists())
                 {
                     receiptFile.CreateNewFile();
                 }
                 FileWriter writer = new FileWriter(receiptFile);
                 writer.Append(data);
                 writer.Flush();
                 writer.Close();
                return true;
                 /*OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.OpenFileOutput(fileName + ".txt", FileCreationMode.Private));
                 outputStreamWriter.Write(data);
                 outputStreamWriter.Close();
                 */
            }
            catch (IOException e)
            {
               MainActivity.ShowMessage("File write failed: " + e.ToString(),"Error");
                return false;
            }
        }

    }
}