package com.example.mountaintravel.service;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import com.example.mountaintravel.variable.Variable;
import com.smart.gtstrvl.GameManagerActivity;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.View;

public class MyService extends Service {
	private static final String TAG = "Service";
	public MyBinder mBinder = new MyBinder();
	String hourbegin = null;
	String min = null;
	String ss = null;
	boolean official = false;
	boolean manager = false;
	String ifBegin = null;
	public static boolean timer = false;
	Thread thread;
	private static boolean flog = false;

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub\
		Log.d(TAG, "onCreate");
		flog = false;

		super.onCreate();
	}

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		Bundle bundle = intent.getExtras();
		return mBinder;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		// TODO Auto-generated method stub
		thread = new Thread(new MyThread());
		/*
		 * 服务开启拿到赛事的一系列信息来显示相应的状态
		 * */
		if (intent!=null) {
		Log.d(TAG, "onStartCommand");
		hourbegin = intent.getStringExtra("hour");
		Log.d(TAG, hourbegin);
		min = intent.getStringExtra("min");
		ss = intent.getStringExtra("ss");
		official = intent.getBooleanExtra("official", false);
		manager = intent.getBooleanExtra("manager", false);
		Log.d(TAG, manager + "");
		ifBegin = intent.getStringExtra("ifBegin");
		Log.d(TAG, ifBegin);
		if (official && ifBegin.equals("未开始")) {
			timer = false;
			GameManagerActivity.gamemana_tv.setVisibility(View.GONE);
			GameManagerActivity.gamemana_tv2.setVisibility(View.GONE);
		} else if (official && ifBegin.equals("已开始")) {
			timer = false;
			GameManagerActivity.gamemana_tv.setVisibility(View.GONE);
			GameManagerActivity.gamemana_tv2.setVisibility(View.GONE);
			clock();
		}
		if (!official && manager && ifBegin.equals("未开始")) {
			timer = false;
			Variable.recLen1 = 0;
			Variable.recLen2 = 0;
			Variable.recLen3 = 0;
			Variable.recLen4 = 0;
			Variable.recLen5 = 0;
			Variable.recLen6 = 0;
			GameManagerActivity.gamemana_tv.setVisibility(View.VISIBLE);
			Log.d(TAG, "开始比赛");
			GameManagerActivity.gamemana_tv.setVisibility(View.VISIBLE);
			GameManagerActivity.gamemana_tv2.setVisibility(View.GONE);
			GameManagerActivity.ifStart=false;

		}
		if (!official && manager && ifBegin.equals("已开始")) {
			timer = false;// 服务器时间减去真实开始时间
			GameManagerActivity.gamemana_tv.setVisibility(View.VISIBLE);
			GameManagerActivity.gamemana_tv.setText("结束比赛");
			GameManagerActivity.gamemana_tv.setVisibility(View.GONE);
			GameManagerActivity.gamemana_tv2.setVisibility(View.VISIBLE);
			GameManagerActivity.ifStart=true;
			clock();
			
		}
		if (!official && !manager && ifBegin.equals("未开始")) {
			timer = false;
			GameManagerActivity.gamemana_tv.setVisibility(View.GONE);
			GameManagerActivity.gamemana_tv2.setVisibility(View.GONE);
			GameManagerActivity.ifStart=false;
		}
		if (!official && !manager && ifBegin.equals("已开始")) {
			GameManagerActivity.gamemana_tv.setVisibility(View.GONE);
			GameManagerActivity.gamemana_tv2.setVisibility(View.GONE);
			GameManagerActivity.ifStart=true;
			timer = false;// 服务器时间减去真实开始时间
			clock();
		}
		}
		return super.onStartCommand(intent, flags, startId);

	}

	private void clock() {
		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				loginByHttpClientSys();
			}
		}).start();

	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		Log.d(TAG, "onDestroy");

		flog = true;
		if (thread.isAlive()) {
			thread.interrupt();
		}

	}

	public class MyBinder extends Binder {

		public void startDownload() {
			Log.d("TAG", "startDownload() executed");
			// 执行具体的下载任务
			if (timer) {

				thread.start();
			}

		}

	}
/*
 * 赛事时间计时器算法逢十进一
 * */
	final Handler handler = new Handler() { // handle
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				Variable.recLen1++;
				if (Variable.recLen1 > 9) {
					GameManagerActivity.tvclock1.setText("" + 0);
				} else {
					GameManagerActivity.tvclock1.setText("" + Variable.recLen1);
				}
				if (Variable.recLen1 > 9) {
					Variable.recLen1 = 0;
					Variable.recLen2++;

				}
				if (Variable.recLen2 > 5) {
					GameManagerActivity.tvclock2.setText("" + 0);
				} else {
					GameManagerActivity.tvclock2.setText("" + Variable.recLen2);
				}
				if (Variable.recLen2 > 5) {
					Variable.recLen2 = 0;
					Variable.recLen3++;

				}
				if (Variable.recLen3 > 9) {
					GameManagerActivity.tvclock4.setText("" + 0);
				} else {
					GameManagerActivity.tvclock4.setText("" + Variable.recLen3);
				}
				if (Variable.recLen3 > 9) {
					Variable.recLen3 = 0;
					Variable.recLen4++;

				}
				if (Variable.recLen4 > 5) {
					GameManagerActivity.tvclock5.setText("" + 0);
				} else {
					GameManagerActivity.tvclock5.setText("" + Variable.recLen4);
				}
				if (Variable.recLen4 > 5) {
					Variable.recLen4 = 0;
					Variable.recLen5++;

				}
				if (Variable.recLen5 > 9) {
					GameManagerActivity.tvclock7.setText("" + 0);
				} else {
					GameManagerActivity.tvclock7.setText("" + Variable.recLen5);
				}
				if (Variable.recLen5 > 9) {
					Variable.recLen5 = 0;
					Variable.recLen6++;

				}
				if (Variable.recLen6 > 2) {

				} else {
					GameManagerActivity.tvclock8.setText("" + Variable.recLen6);
				}
			}
			super.handleMessage(msg);
		}
	};

	public void bu1(View v) {

	}

	public class MyThread implements Runnable { // thread
		public void run() {

			while (!flog) {
				try {
					Thread.sleep(1000); // sleep 1000ms
					Message message = new Message();
					message.what = 1;
					handler.sendMessage(message);
				} catch (Exception e) {
				}
			}
		}
	}

	private void loginByHttpClientSys() {
		// TODO Auto-generated method stub
		DefaultHttpClient client = new DefaultHttpClient();
		String uri = "http://" + Variable.address + "/terminal/systime";
		HttpPost httpPost = new HttpPost(uri);
		try {
			List<NameValuePair> parameters = new ArrayList<NameValuePair>();
			// 往这个集合中添加你要传递的参数
			// 创建传递参数封装 实体对象
			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters,
					"UTF-8");// 设置传递参数的编码
			// 把实体对象存入到httpPost对象中
			httpPost.setEntity(entity);
			HttpResponse response = client.execute(httpPost); // HttpUriRequest的后代对象
			if (response.getStatusLine().getStatusCode() == 200) {

				HttpEntity entity1 = response.getEntity();
				String result = EntityUtils.toString(response.getEntity(),
						"UTF-8");
				// String result = StreamTools.streamToString(is);
				String time = Variable.getStrTime2(result);
				String hourmin = time.substring(8, 14);
				String hour = hourmin.substring(0, 2);
				String minute = hourmin.substring(2, 4);
				String second = hourmin.substring(4);
				int i1 = Integer.parseInt(hour);
				int j1 = Integer.parseInt(hourbegin);
				int j2 = Integer.parseInt(min);
				int j3 = Integer.parseInt(ss);
				int i2 = Integer.parseInt(minute);
				int i3 = Integer.parseInt(second);
				int i = i1 * 60 * 60 + i2 * 60 + i3;
				int j = j1 * 3600 + j2 * 60+j3;
				int a = i - j;
				int a1 = a % 60;
				int a2 = a / 60 % 60;
				int a3 = a / 3600;
				int b1 = a1 % 10;
				int b2 = a1 / 10;
				int b3 = a2 % 10;
				int b4 = a2 / 10;
				int b5 = a3 % 10;
				int b6 = a3 / 10;
				Variable.recLen1 = b1;
				Variable.recLen2 = b2;
				Variable.recLen3 = b3;
				Variable.recLen4 = b4;
				Variable.recLen5 = b5;
				Variable.recLen6 = b6;
				thread.start();
			}

		}

		catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			// 6. 释放连接。无论执行方法是否成功，都必须释放连接
			client.getConnectionManager().shutdown();
		}
	}

}
