/*
 * 
 * ClickCounter by Fabian Schlieper
 *
 * License:
 * Creative Commons Attribution 3.0 Unported
 * http://creativecommons.org/licenses/by/3.0/ 
 * 
 */

using System;
using System.Drawing;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;

namespace ClickCounter
{
    partial class MainForm : Form
    {
        private int clicks;
        private ulong totalClicks;
        private int maxClickRate;
        private bool running;
        private int tmpN;

        string titleFormat;

        public MainForm()
        {
            InitializeComponent();
            this.Icon = Icon.ExtractAssociatedIcon(Application.ExecutablePath);

            clicks = 0;
            maxClickRate = 0;
            totalClicks = 0;
            running = true;

            long ticks = DateTime.Now.Ticks;

            Thread thread = new Thread(new ThreadStart(runClickCounter));
            thread.Start();

            CultureInfo german = CultureInfo.GetCultureInfo("de");

            if (CultureInfo.CurrentCulture.Equals(german) || CultureInfo.CurrentCulture.Parent.Equals(german))
            {
                lbLabel.Text = "Klicks pro Sekunde";
                titleFormat = "{0} Klicks pro Sekunde";
            }
            else
            {
                lbLabel.Text = "Clicks per second";
                titleFormat = "{0} clicks per second";
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            totalClicks += (ulong)clicks;
            tmpN = (5000 + clicks * 20);
            if (clicks > maxClickRate)
                maxClickRate = clicks;

            Text = String.Format(titleFormat, clicks);
            lbClicksVal.Text = clicks.ToString();
            lbMaxClickRate.Text = String.Format("Max.: {0}  Total: {1}", maxClickRate, totalClicks);
            clicks = 0;
        }


        private void runClickCounter()
        {
            bool wasPressed = false;

            int i = 0;

            while (running)
            {
                bool isPressed = MouseIsPressed();

                if (isPressed && !wasPressed)
                    clicks++;

                wasPressed = isPressed;

                if (i++ >= tmpN)
                {
                    Thread.Sleep(1);
                    i = 0;
                }
            }
        }


        [DllImport("user32.dll")]
        static extern short GetAsyncKeyState(Keys vKey);

        private static bool MouseIsPressed()
        {
            return (GetAsyncKeyState(Keys.LButton) != 0);
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            running = false;
        }

        private void llbWebsite_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            System.Diagnostics.Process.Start(llbWebsite.Text);
        }
    }
}