﻿using System;
using System.Linq;
using Xamarin.Forms;
using System.Collections.Generic;
using CalculatorsLibrary.CalculatorsLibrary;
using Plugin.Share;
using Plugin.Share.Abstractions;

namespace Calculators
{
    public partial class ThreadProgramPage : ContentPage
    {
        void Handle_Clicked(object sender, System.EventArgs e)
        {
            throw new NotImplementedException();
        }

        BasicOperation BasicOperation { get; set; }

        string ClipboardText { get; set; }

        public ThreadProgramPage(Parameter parameter, ITabbedPageSubjectButton subject)
        {
            BasicOperation = (subject as TabbedTemplatePage).BasicOperation;

            if (parameter.ID == CalculatorsLibrary.Enumeration.ParameterEnum.ThreadProgramGenerator)
                parameter.Calculate();

            var bindingContext = SetUpSourceList(parameter.ValueString);
            ClipboardText = SetUpClipboardText(bindingContext);

            if (bindingContext.Count > 1)
                ToolbarItems.Add(new ToolbarItem()
	            {
	                Icon = "share",
	                Command = new Command(() => ShareMenuItem_OnClicked()),
	                Order = ToolbarItemOrder.Primary
	            });

			BindingContext = bindingContext;

            InitializeComponent();

			Resx.Translation.SetNavigationBackProperty(this);
        }



        void ShareMenuItem_OnClicked()
        {
            if (!CrossShare.IsSupported || string.IsNullOrWhiteSpace(ClipboardText))
                return;

            CrossShare.Current.Share(new ShareMessage()
            {
				Title = string.Format("{0} {1} - Dormer Pramet", Resx.Translation.TranslateString("Example"), Resx.Translation.TranslateString("MillingThread").ToLower()),
                Text = ClipboardText 
            });
        }

        List<ThreadProgramModel> SetUpSourceList(string sourceString)
		{
            // Check if there is a program generated. If not, show the WarningCell
            if (string.IsNullOrWhiteSpace(sourceString))
                return new List<ThreadProgramModel> { new ThreadProgramModel { TypeCell = ThreadProgramTypeCell.WarningCell, Text = "Error" } };

            // The bindingcontext of the page is a list. Therefore, the string must be splitup in several strings. 
			string[] splittedSourceString = sourceString.Split(new[] { "\\n" }, StringSplitOptions.RemoveEmptyEntries);
            var sourceList = new List<ThreadProgramModel>();

            for (int index = 0; index <= (splittedSourceString.Length - 1); index++)
                sourceList.Add(new ThreadProgramModel { TypeCell = ThreadProgramTypeCell.NormalCell, Text = splittedSourceString[index], Index = index });

            return sourceList;
		}

        string SetUpClipboardText(List<ThreadProgramModel> sourceList)
        {
            // Check if the bindingcontext contains the warming cell
            if ((sourceList.FirstOrDefault(i => i.TypeCell == ThreadProgramTypeCell.WarningCell)) != null) 
                return string.Empty;

            // Make a string of the list seperated by newlines.
            var clipboardText = "";
            foreach(var model in sourceList)
                clipboardText = clipboardText + string.Format("{0}\t{1}", model.RuleNumber, model.Text) + Environment.NewLine;

            return clipboardText;
		}
    }
}
 