using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Essentials;
using Xamarin.Forms;
using ZXing.Net.Mobile.Forms;

namespace BarcodeReader
{
	public partial class MainPage : ContentPage
	{
		public MainPage()
		{
			InitializeComponent();
			InitInstance();
		}

		private void InitInstance()
		{
			TapGestureRecognizer copyClipbaordTap = new TapGestureRecognizer();
			copyClipbaordTap.Tapped += CopyClipbaordTap_Tapped;
			codeLabel.GestureRecognizers.Add(copyClipbaordTap);
		}

		private void CopyClipbaordTap_Tapped(object sender, EventArgs e)
		{
			Label label = sender as Label;
			if (label == null)
				return;

			Clipboard.SetTextAsync(label.Text);

			DisplayAlert("알림", $"바코드가 클립보드에 복사되었습니다.", "확인");
		}

		private async void barcodeReadButton_Clicked(object sender, EventArgs e)
		{
			ZXingScannerPage scannerPage = new ZXingScannerPage();
			await Navigation.PushAsync(scannerPage);
			scannerPage.OnScanResult += ScannerPage_OnScanResult;
		}

		private void ScannerPage_OnScanResult(ZXing.Result result)
		{
			Device.BeginInvokeOnMainThread(async () =>
			{
				timeStampLabel.Text = $"타임스탬프: {DateTime.FromBinary(result.Timestamp)}";
				formatLabel.Text = $"바코드 포맷: {result.BarcodeFormat}";
				codeLabel.Text = result.Text;

				await Navigation.PopAsync();
			});
		}
	}
}
