using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Devices.Radio;

namespace WPFMRadio
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        public MainPage()
        {
            InitializeComponent();
            //Instanz der FMRadio Klasse holen
            Microsoft.Devices.Radio.FMRadio fmRadio = Microsoft.Devices.Radio.FMRadio.Instance;
            //Das Radio einschalten
            fmRadio.PowerMode = RadioPowerMode.On;
            //Warten bis das Radio initialisiert ist
            System.Threading.Thread.Sleep(2000);
            //Region auf Europa setzen
            fmRadio.CurrentRegion = RadioRegion.Europe;
            //Eine bekannte Radiosenderfrequenz einstellen
            fmRadio.Frequency = 106.7;
            System.Threading.Thread.Sleep(2000);
            textBlock1.Text = fmRadio.Frequency.ToString();
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            Microsoft.Devices.Radio.FMRadio fmRadio = Microsoft.Devices.Radio.FMRadio.Instance;
            bool boFirst = true;
            //Diese Werte Variiern je nach Modell und verwendetem Chipsatz
            //Diese Werte funktionieren auf dem LG GW910 (Developer Testgerät) sowie dem HTC7 Mozart
            while (boFirst || fmRadio.SignalStrength < 1.0D || fmRadio.SignalStrength > 2.5D)
            {
                boFirst = false;
                Decimal d1 = (decimal)fmRadio.Frequency;
                d1 += (decimal)0.1;
                if (d1 > 108)
                {
                    d1 = (decimal)87.5;
                }
                fmRadio.Frequency =(double) d1;
                //Warten bis sich die Frequenz eingestellt hat, sons ist eventuell das Signal noch nicht korrekt,
                System.Threading.Thread.Sleep(1000);
            }
            textBlock1.Text = fmRadio.Frequency.ToString();
        }

        private void button2_Click(object sender, RoutedEventArgs e)
        {
            Microsoft.Devices.Radio.FMRadio fmRadio = Microsoft.Devices.Radio.FMRadio.Instance;
            MessageBox.Show(fmRadio.SignalStrength.ToString(), "Frequenz: " + fmRadio.Frequency.ToString() + " Signal:", MessageBoxButton.OK);
        }
    }
}
